Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Java to Perl with equivalent syntax and logic.
import java.util.TreeSet; public class Farey{ private static class Frac implements Comparable<Frac>{ int num; int den; public Frac(int num, int den){ this.num = num; this.den = den; } @Override public String toString(){ return num + "/" + den; } @Override public int compareTo(Frac o){ ...
use warnings; use strict; use Math::BigRat; use ntheory qw/euler_phi vecsum/; sub farey { my $N = shift; my @f; my($m0,$n0, $m1,$n1) = (0, 1, 1, $N); push @f, Math::BigRat->new("$m0/$n0"); push @f, Math::BigRat->new("$m1/$n1"); while ($f[-1] < 1) { my $m = int( ($n0 + $N) / $n1) * $m1 - $m0; my $n ...
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static...
use ntheory qw/divisor_sum/; sub aliquot { my($n, $maxterms, $maxn) = @_; $maxterms = 16 unless defined $maxterms; $maxn = 2**47 unless defined $maxn; my %terms = ($n => 1); my @allterms = ($n); for my $term (2 .. $maxterms) { $n = divisor_sum($n)-$n; last if $n > $maxn; return ("terminat...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static...
use ntheory qw/divisor_sum/; sub aliquot { my($n, $maxterms, $maxn) = @_; $maxterms = 16 unless defined $maxterms; $maxn = 2**47 unless defined $maxn; my %terms = ($n => 1); my @allterms = ($n); for my $term (2 .. $maxterms) { $n = divisor_sum($n)-$n; last if $n > $maxn; return ("terminat...
Maintain the same structure and functionality when rewriting this code in Perl.
public class ImplicitTypeConversion{ public static void main(String...args){ System.out.println( "Primitive conversions" ); byte by = -1; short sh = by; int in = sh; long lo = in; System.out.println( "byte value -1 to 3 integral types: " + lo ); float fl = ...
print 1 + '2'; print '1' + '2'; print 1 . 1; $a = 1; $b = 2; say "$a+$b"; say hex int( (2 . 0 x '2') ** substr 98.5, '2', '2' ) . 'beef';
Please provide an equivalent version of this Java code in Perl.
public class ImplicitTypeConversion{ public static void main(String...args){ System.out.println( "Primitive conversions" ); byte by = -1; short sh = by; int in = sh; long lo = in; System.out.println( "byte value -1 to 3 integral types: " + lo ); float fl = ...
print 1 + '2'; print '1' + '2'; print 1 . 1; $a = 1; $b = 2; say "$a+$b"; say hex int( (2 . 0 x '2') ** substr 98.5, '2', '2' ) . 'beef';
Write the same algorithm in Perl as shown in this Java implementation.
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th ma...
use strict; use warnings; use feature 'say'; use ntheory 'is_prime'; sub magnanimous { my($n) = @_; my $last; for my $c (1 .. length($n) - 1) { ++$last and last unless is_prime substr($n,0,$c) + substr($n,$c) } not $last; } my @M; for ( my $i = 0, my $count = 0; $count < 400; $i++ ) { ...
Write a version of this Java function in Perl with identical behavior.
import java.math.BigInteger; public class MersennePrimes { private static final int MAX = 20; private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TWO = BigInteger.valueOf(2); private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 =...
use ntheory qw/forprimes is_mersenne_prime/; forprimes { is_mersenne_prime($_) && say } 1e9;
Port the following code from Java to Perl with equivalent syntax and logic.
import java.math.BigInteger; public class MersennePrimes { private static final int MAX = 20; private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TWO = BigInteger.valueOf(2); private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 =...
use ntheory qw/forprimes is_mersenne_prime/; forprimes { is_mersenne_prime($_) && say } 1e9;
Port the following code from Java to Perl with equivalent syntax and logic.
import java.util.ArrayList; import java.util.List; public class SexyPrimes { public static void main(String[] args) { sieve(); int pairs = 0; List<String> pairList = new ArrayList<>(); int triples = 0; List<String> tripleList = new ArrayList<>(); int quadruplets = 0...
use ntheory qw/prime_iterator is_prime/; sub tuple_tail { my($n,$cnt,@array) = @_; $n = @array if $n > @array; my @tail; for (1..$n) { my $p = $array[-$n+$_-1]; push @tail, "(" . join(" ", map { $p+6*$_ } 0..$cnt-1) . ")"; } return @tail; } sub comma { (my $s = reverse shif...
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.PriorityQueue; import java.util.ArrayList; import java.util.List; import java.util.Iterator; class CubeSum implements Comparable<CubeSum> { public long x, y, value; public CubeSum(long x, long y) { this.x = x; this.y = y; this.value = x*x*x + y*y*y; } public String toString() { return St...
my($beg, $end) = (@ARGV==0) ? (1,25) : (@ARGV==1) ? (1,shift) : (shift,shift); my $lim = 1e14; my @basis = map { $_*$_*$_ } (1 .. int($lim ** (1.0/3.0) + 1)); my $paira = 2; my ($segsize, $low, $high, $i) = (500_000_000, 0, 0, 0); while ($i < $end) { $low = $high+1; die "lim too low" if $low > $lim; $high ...
Preserve the algorithm and functionality while converting the code from Java to Perl.
public class StrongAndWeakPrimes { private static int MAX = 10_000_000 + 1000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { sieve(); System.out.println("First 36 strong primes:"); displayStrongPrimes(36); for ( int n :...
use ntheory qw(primes vecfirst); sub comma { (my $s = reverse shift) =~ s/(.{3})/$1,/g; $s =~ s/,(-?)$/$1/; $s = reverse $s; } sub below { my ($m, @a) = @_; vecfirst { $a[$_] > $m } 0..$ my (@strong, @weak, @balanced); my @primes = @{ primes(10_000_019) }; for my $k (1 .. $ my $x = ($primes[$k - 1] ...
Write the same code in Perl as shown below in Java.
import java.math.BigInteger; public class LeftFac{ public static BigInteger factorial(BigInteger n){ BigInteger ans = BigInteger.ONE; for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){ ans = ans.multiply(x); } return ans; } public static BigInteger leftFact(BigInteger n...
use 5.010; use strict; use warnings; use bigint; sub leftfact { my ($n) = @_; state $cached = 0; state $factorial = 1; state $leftfact = 0; if( $n < $cached ) { ($cached, $factorial, $leftfact) = (0, 1, 0); } while( $n > $cached ) { $leftfact += $factorial; $factorial *= ++$cached; } return $leftfact; ...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.math.BigInteger; public class LeftFac{ public static BigInteger factorial(BigInteger n){ BigInteger ans = BigInteger.ONE; for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){ ans = ans.multiply(x); } return ans; } public static BigInteger leftFact(BigInteger n...
use 5.010; use strict; use warnings; use bigint; sub leftfact { my ($n) = @_; state $cached = 0; state $factorial = 1; state $leftfact = 0; if( $n < $cached ) { ($cached, $factorial, $leftfact) = (0, 1, 0); } while( $n > $cached ) { $leftfact += $factorial; $factorial *= ++$cached; } return $leftfact; ...
Port the provided Java code into Perl while preserving the original functionality.
import java.util.*; public class StrangeUniquePrimeTriplets { public static void main(String[] args) { strangeUniquePrimeTriplets(30, true); strangeUniquePrimeTriplets(1000, false); } private static void strangeUniquePrimeTriplets(int limit, boolean verbose) { boolean[] sieve = pri...
use strict; use warnings; use List::Util 'sum'; use ntheory <primes is_prime>; use Algorithm::Combinatorics 'combinations'; for my $n (30, 1000) { printf "Found %d strange unique prime triplets up to $n.\n", scalar grep { is_prime(sum @$_) } combinations(primes($n), 3); }
Generate an equivalent Perl version of this Java code.
import java.util.*; public class StrangeUniquePrimeTriplets { public static void main(String[] args) { strangeUniquePrimeTriplets(30, true); strangeUniquePrimeTriplets(1000, false); } private static void strangeUniquePrimeTriplets(int limit, boolean verbose) { boolean[] sieve = pri...
use strict; use warnings; use List::Util 'sum'; use ntheory <primes is_prime>; use Algorithm::Combinatorics 'combinations'; for my $n (30, 1000) { printf "Found %d strange unique prime triplets up to $n.\n", scalar grep { is_prime(sum @$_) } combinations(primes($n), 3); }
Port the following code from Java to Perl with equivalent syntax and logic.
public class Strange { private static final boolean[] p = { false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; public static boolean isstrange(long n) { if (n < 10) return false; ...
use strict; use warnings; use feature 'say'; use ntheory 'is_prime'; my($low, $high) = (100, 500); my $n = my @SP = grep { my @d = split ''; is_prime $d[0]+$d[1] and is_prime $d[1]+$d[2] } $low+1 .. $high-1; say "Between $low and $high there are $n strange-plus numbers:\n" . (sprintf "@{['%4d' x $n]}", @SP[0..$n-1...
Convert this Java snippet to Perl and keep its semantics consistent.
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isP...
use strict; use warnings; use feature 'say'; use feature 'state'; use ntheory qw<is_prime>; use Lingua::EN::Numbers qw(num2en_ordinal); my @prime_digits = <2 3 5 7>; my @spds = grep { is_prime($_) && /^[@{[join '',@prime_digits]}]+$/ } 1..100; my @p = map { $_+3, $_+7 } map { 10*$_ } @prime_digits; while ($ st...
Port the following code from Java to Perl with equivalent syntax and logic.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { D...
use Imager; sub plasma { my ($w, $h) = @_; my $img = Imager->new(xsize => $w, ysize => $h); for my $x (0 .. $w-1) { for my $y (0 .. $h-1) { my $hue = 4 + sin($x/19) + sin($y/9) + sin(($x+$y)/25) + sin(sqrt($x**2 + $y**2)/8); $img->setpixel(x => $x, y => $y, color => {hsv =...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long ...
use ntheory qw/is_square_free moebius/; sub square_free_count { my ($n) = @_; my $count = 0; foreach my $k (1 .. sqrt($n)) { $count += moebius($k) * int($n / $k**2); } return $count; } print "Square─free numbers between 1 and 145:\n"; print join(' ', grep { is_square_free($_) } 1 .. 145), ...
Produce a language-to-language conversion: from Java to Perl, same semantics.
public class SelfNumbers { private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1; private static final boolean[] SV = new boolean[MC + 1]; private static void sieve() { int[] dS = new int[10_000]; for (int a = 9, i = 9999; a >= 0; a--) { for (int b = 9; b >= 0; b--) { ...
use strict; use warnings; use feature 'say'; use List::Util qw(max sum); my ($i, $pow, $digits, $offset, $lastSelf, @selfs) = ( 1, 10, 1, 9, 0, ); my $final = 50; while () { my $isSelf = 1; my $sum = my $start = sum split //, max(($i-$offset), 0); for ( my $j = $start; $j < $i; ...
Transform the following Java implementation into Perl, maintaining the same output and logic.
public class NivenNumberGaps { public static void main(String[] args) { long prevGap = 0; long prevN = 1; long index = 0; System.out.println("Gap Gap Index Starting Niven"); for ( long n = 2 ; n < 20_000_000_000l ; n++ ) { if ( isNiven(n) ) { ...
use strict; use warnings; use List::Util 'sum'; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } my ($index, $last, $gap, $count) = (0, 0, 0, 0); my $threshold = 10_000_000; print "Gap Index of gap Starting Niven\n"; while (1) { $count++; next unless 0 == $count % sum split //, $coun...
Write the same code in Perl as shown below in Java.
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0....
sub convert { my($magnitude, $unit) = @_; my %factor = ( tochka => 0.000254, liniya => 0.00254, diuym => 0.0254, vershok => 0.04445, piad => 0.1778, fut => 0.3048, arshin => 0.7112, sazhen => 2.1336, ve...
Translate this program into Perl but keep the logic exactly as in Java.
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; } public static void main(String[] args) { ...
use strict; use warnings; use feature 'say'; sub pancake { my($n) = @_; my ($gap, $sum, $adj) = (2, 2, -1); while ($sum < $n) { $sum += $gap = $gap * 2 - 1 and $adj++ } $n + $adj; } my $out; $out .= sprintf "p(%2d) = %2d ", $_, pancake $_ for 1..20; say $out =~ s/.{1,55}\K /\n/gr; sub pancake2 { ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); ...
my $N = 2200; push @sq, $_**2 for 0 .. $N; my @not = (0) x $N; @not[0] = 1; for my $d (1 .. $N) { my $last = 0; for my $a (reverse ceiling($d/3) .. $d) { for my $b (1 .. ceiling($a/2)) { my $ab = $sq[$a] + $sq[$b]; last if $ab > $sq[$d]; my $x = sqrt($sq[$d] - $ab);...
Rewrite the snippet below in Perl so it works the same as the original Java code.
package org.rosettacode; import java.util.ArrayList; import java.util.List; public class SumAndProductPuzzle { private final long beginning; private final int maxSum; private static final int MIN_VALUE = 2; private List<int[]> firstConditionExcludes = new ArrayList<>(); private List<int[]> secon...
use List::Util qw(none); sub grep_unique { my($by, @list) = @_; my @seen; for (@list) { my $x = &$by(@$_); $seen[$x]= defined $seen[$x] ? 0 : join ' ', @$_; } grep { $_ } @seen; } sub sums { my($n) = @_; my @sums; push @sums, [$_, $n - $_] for 2 .. int $n/2; @sums; ...
Generate an equivalent Perl version of this Java code.
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,...
use ntheory qw/forperm/; for my $len (1..8) { my($pre, $post, $t) = ("",""); forperm { $t = join "",@_; $post .= $t unless index($post ,$t) >= 0; $pre = $t . $pre unless index($pre, $t) >= 0; } $len; printf "%2d: %8d %8d\n", $len, length($pre), length($post); }
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.math.BigDecimal; import java.util.List; public class TestIntegerness { private static boolean isLong(double d) { return isLong(d, 0.0); } private static boolean isLong(double d, double tolerance) { return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance; ...
use Math::Complex; sub is_int { my $number = shift; if (ref $number eq 'Math::Complex') { return 0 if $number->Im != 0; $number = $number->Re; } return int($number) == $number; } for (5, 4.1, sqrt(2), sqrt(4), 1.1e10, 3.0-0.0*i, 4-3*i, 5.6+0*i) { printf "%20s is%s an inte...
Write the same code in Perl as shown below in Java.
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.text.NumberFormat; import java.time.Duration; import java.util.Timer; import java.util.TimerTask; public class Main { public static void main(String[] args) throws FileNotFoundExcep...
$last_total = 0; $last_idle = 0; while () { @cpu = split /\s+/, `head -1 /proc/stat`; shift @cpu; $this_total = 0; $this_total += $_ for @cpu; $delta_total = $this_total - $last_total; $this_idle = $cpu[3] - $last_idle; $delta_idle = $this_idle - $last_idle; $last_total = $th...
Keep all operations the same but rewrite the snippet in Perl.
public class UlamNumbers { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int n = 1; n <= 100000; n *= 10) { System.out.printf("Ulam(%d) = %d\n", n, ulam(n)); } long finish = System.currentTimeMillis(); System.out.printf("El...
use strict; use warnings; use feature <say state>; sub ulam { my($n) = @_; state %u = (1 => 1, 2 => 1); state @ulams = <0 1 2>; return $ulams[$n] if $ulams[$n]; $n++; my $i = 3; while () { my $count = 0; $u{ $i - $ulams[$_] } and $ulams[$_] != $i - $ula...
Translate the given Java code snippet into Perl without altering its behavior.
import java.util.Arrays; import java.util.stream.IntStream; public class RamseysTheorem { static char[][] createMatrix() { String r = "-" + Integer.toBinaryString(53643); int len = r.length(); return IntStream.range(0, len) .mapToObj(i -> r.substring(len - i) + r.substring(...
use ntheory qw(forcomb); use Math::Cartesian::Product; $n = 17; push @a, [(0) x $n] for 0..$n-1; $a[$_][$_] = '-' for 0..$n-1; for $x (cartesian {@_} [(0..$n-1)], [(1,2,4,8)]) { $i = @$x[0]; $k = @$x[1]; $j = ($i + $k) % $n; $a[$i][$j] = $a[$j][$i] = 1; } forcomb { my $l = 0; @i = @_; for...
Produce a language-to-language conversion: from Java to Perl, same semantics.
public class TypeDetection { private static void showType(Object a) { if (a instanceof Integer) { System.out.printf("'%s' is an integer\n", a); } else if (a instanceof Double) { System.out.printf("'%s' is a double\n", a); } else if (a instanceof Character) { ...
$scalar = 1; @array = (1, 2); %hash = ('a' => 1); $regex = qr/foo.*bar/; $reference = \%hash; sub greet { print "Hello world!" }; $subref = \&greet; $fmt = "%-11s is type: %s\n"; printf $fmt, '$scalar', ref(\$scalar); printf $fmt, '@array', ref(\@array); printf $fmt, '%hash', ref(\%hash...
Rewrite the snippet below in Perl so it works the same as the original Java code.
public class SafePrimes { public static void main(String... args) { int SIEVE_SIZE = 10_000_000; boolean[] isComposite = new boolean[SIEVE_SIZE]; isComposite[0] = true; isComposite[1] = true; for (int n = 2; n < SIEVE_SIZE; n++) { if (isComposite...
use ntheory qw(forprimes is_prime); my $upto = 1e7; my %class = ( safe => [], unsafe => [2] ); forprimes { push @{$class{ is_prime(($_-1)>>1) ? 'safe' : 'unsafe' }}, $_; } 3, $upto; for (['safe', 35], ['unsafe', 40]) { my($type, $quantity) = @$_; print "The first $quantity $type primes are:\n"; prin...
Produce a language-to-language conversion: from Java to Perl, same semantics.
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...
use Data::Dumper qw(Dumper); sub hashJoin { my ($table1, $index1, $table2, $index2) = @_; my %h; foreach my $s (@$table1) { push @{ $h{$s->[$index1]} }, $s; } map { my $r = $_; map [$_, $r], @{ $h{$r->[$index2]} } } @$table2; } @table1 = ([27, "Jonah"], [18, "Alan"], ...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.util.function.Predicate; public class PermutationsWithRepetitions { public static void main(String[] args) { char[] chars = {'a', 'b', 'c', 'd'}; permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0); } static void permute(char[] a, int k, Predicate<int[]> decid...
use Algorithm::Combinatorics qw/tuples_with_repetition/; print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.util.function.Predicate; public class PermutationsWithRepetitions { public static void main(String[] args) { char[] chars = {'a', 'b', 'c', 'd'}; permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0); } static void permute(char[] a, int k, Predicate<int[]> decid...
use Algorithm::Combinatorics qw/tuples_with_repetition/; print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.function.IntPredicate; import java.util.stream.IntStream; public class Test { public static void main(String[] args) throws Exception { print("Java Identifier start: ", 0, 0x10FFFF, 72, Character::isJavaIdentifierStart, "%c"); print("Java Identifier part: ...
for $i (0..0x7f) { $c = chr($i); print $c if $c =~ /\w/; } use utf8; binmode STDOUT, ":utf8"; for (0..0x1ffff) { $c = chr($_); print $c if $c =~ /\p{Word}/; }
Port the provided Java code into Perl while preserving the original functionality.
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.File; import java.io.IOException; import java.util.Scanner; class CopysJ { public static void main(String[] args) { String ddname_IN = "copys.in.txt"; String ddname_OUT = "copys.out.txt"; if (args.length >= 1) { ddname_IN = args[...
my %F = ( 'field a' => { offset => 0, length => 5, type => 'Str' }, 'field b' => { offset => 5, length => 5, type => 'Str' }, 'field c' => { offset => 10, length => 4, type => 'Bit' }, 'field d' => { offset => 14, length => 1, type => 'Str' }, 'field e' => { offset => 15, length => 5, type => 'St...
Convert this Java block to Perl, preserving its control flow and logic.
public class PreserveScreen { public static void main(String[] args) throws InterruptedException { System.out.print("\033[?1049h\033[H"); System.out.println("Alternate screen buffer\n"); for (int i = 5; i > 0; i--) { String s = (i > 1) ? "s" : ""; System.out.printf("\...
print "\033[?1049h\033[H"; print "Alternate screen buffer\n"; for (my $i = 5; $i > 0; --$i) { print "going back in $i...\n"; sleep(1); } print "\033[?1049l";
Translate the given Java code snippet into Perl without altering its behavior.
import java.math.BigInteger; import java.util.*; class LeftTruncatablePrime { private static List<BigInteger> getNextLeftTruncatablePrimes(BigInteger n, int radix, int millerRabinCertainty) { List<BigInteger> probablePrimes = new ArrayList<BigInteger>(); String baseString = n.equals(BigInteger.ZERO) ? "" :...
use ntheory qw/:all/; use Math::GMPz; sub lltp { my($n, $b, $best) = (shift, Math::GMPz->new(1)); my @v = map { Math::GMPz->new($_) } @{primes($n-1)}; while (@v) { $best = vecmax(@v); $b *= $n; my @u; foreach my $vi (@v) { push @u, grep { is_prob_prime($_) } map { $vi + $_*$b } 1 .. $n-1; ...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void...
sub permute :prototype(&@) { my $code = shift; my @idx = 0..$ while ( $code->(@_[@idx]) ) { my $p = $ --$p while $idx[$p-1] > $idx[$p]; my $q = $p or return; push @idx, reverse splice @idx, $p; ++$q while $idx[$p-1] > $idx[$q]; @idx[$p-1,$q]=@idx[$q,$p-1]; } } @formats = ( '((%d %s %d) %s...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void...
sub permute :prototype(&@) { my $code = shift; my @idx = 0..$ while ( $code->(@_[@idx]) ) { my $p = $ --$p while $idx[$p-1] > $idx[$p]; my $q = $p or return; push @idx, reverse splice @idx, $p; ++$q while $idx[$p-1] > $idx[$q]; @idx[$p-1,$q]=@idx[$q,$p-1]; } } @formats = ( '((%d %s %d) %s...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class HoughTransform { public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast) { int width = inputData.width; int height = inputData.height; in...
use strict; use warnings; use Imager; use constant pi => 3.14159265; sub hough { my($im) = shift; my($width) = shift || 460; my($height) = shift || 360; $height = 2 * int $height/2; $height = 2 * int $height/2; my($xsize, $ysize) = ($im->getwidth, $im->getheight); my $ht = Imager->...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; public class TonelliShanks { private static final BigInteger ZERO = BigInteger.ZERO; private static final BigInteger ONE = BigInteger.ONE; private static final...
use bigint; use ntheory qw(is_prime powmod kronecker); sub tonelli_shanks { my($n,$p) = @_; return if kronecker($n,$p) <= 0; my $Q = $p - 1; my $S = 0; $Q >>= 1 and $S++ while 0 == $Q%2; return powmod($n,int(($p+1)/4), $p) if $S == 1; my $c; for $n (2..$p) { next if kronecker($...
Port the following code from Java to Perl with equivalent syntax and logic.
import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; public class TonelliShanks { private static final BigInteger ZERO = BigInteger.ZERO; private static final BigInteger ONE = BigInteger.ONE; private static final...
use bigint; use ntheory qw(is_prime powmod kronecker); sub tonelli_shanks { my($n,$p) = @_; return if kronecker($n,$p) <= 0; my $Q = $p - 1; my $S = 0; $Q >>= 1 and $S++ while 0 == $Q%2; return powmod($n,int(($p+1)/4), $p) if $S == 1; my $c; for $n (2..$p) { next if kronecker($...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; public class TruthTable { public static void main( final String... args ) { System.out.println( new Tru...
sub truth_table { my $s = shift; my (%seen, @vars); for ($s =~ /([a-zA-Z_]\w*)/g) { $seen{$_} //= do { push @vars, $_; 1 }; } print "\n", join("\t", @vars, $s), "\n", '-' x 40, "\n"; @vars = map("\$$_", @vars); $s =~ s/([a-zA-Z_]\w*)/\$$1/g; $s = "print(".join(',"\t", ', map(...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; public class TruthTable { public static void main( final String... args ) { System.out.println( new Tru...
sub truth_table { my $s = shift; my (%seen, @vars); for ($s =~ /([a-zA-Z_]\w*)/g) { $seen{$_} //= do { push @vars, $_; 1 }; } print "\n", join("\t", @vars, $s), "\n", '-' x 40, "\n"; @vars = map("\$$_", @vars); $s =~ s/([a-zA-Z_]\w*)/\$$1/g; $s = "print(".join(',"\t", ', map(...
Translate this program into Perl but keep the logic exactly as in Java.
import java.util.Objects; import java.util.function.Predicate; public class RealNumberSet { public enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN, } public static class RealSet { private Double low; private Double high; private Predicate<D...
use utf8; package BNum; use overload ( '""' => \&_str, '<=>' => \&_cmp, ); sub new { my $self = shift; bless [@_], ref $self || $self } sub flip { my @a = @{+shift}; $a[2] = !$a[2]; bless \@a } my $brackets = qw/ [ ( ) ] /; sub _str { my $v = sprintf "%.2f", $_[0][0]; $_[0][2] ? $v . ($_[0][1] == 1...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.util.Objects; import java.util.function.Predicate; public class RealNumberSet { public enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN, } public static class RealSet { private Double low; private Double high; private Predicate<D...
use utf8; package BNum; use overload ( '""' => \&_str, '<=>' => \&_cmp, ); sub new { my $self = shift; bless [@_], ref $self || $self } sub flip { my @a = @{+shift}; $a[2] = !$a[2]; bless \@a } my $brackets = qw/ [ ( ) ] /; sub _str { my $v = sprintf "%.2f", $_[0][0]; $_[0][2] ? $v . ($_[0][1] == 1...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.util.*; import java.util.stream.*; public class StateNamePuzzle { static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas...
use warnings; use strict; use feature qw{ say }; sub uniq { my %uniq; undef @uniq{ @_ }; return keys %uniq } sub puzzle { my @states = uniq(@_); my %pairs; for my $state1 (@states) { for my $state2 (@states) { next if $state1 le $state2; my $both = join q(),...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.math.BigInteger; public class SuperDNumbers { public static void main(String[] args) { for ( int i = 2 ; i <= 9 ; i++ ) { superD(i, 10); } } private static final void superD(int d, int max) { long start = System.currentTimeMillis(); String test ...
use strict; use warnings; use bigint; use feature 'say'; sub super { my $d = shift; my $run = $d x $d; my @super; my $i = 0; my $n = 0; while ( $i < 10 ) { if (index($n ** $d * $d, $run) > -1) { push @super, $n; ++$i; } ++$n; } @super; } ...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.math.BigInteger; public class SuperDNumbers { public static void main(String[] args) { for ( int i = 2 ; i <= 9 ; i++ ) { superD(i, 10); } } private static final void superD(int d, int max) { long start = System.currentTimeMillis(); String test ...
use strict; use warnings; use bigint; use feature 'say'; sub super { my $d = shift; my $run = $d x $d; my @super; my $i = 0; my $n = 0; while ( $i < 10 ) { if (index($n ** $d * $d, $run) > -1) { push @super, $n; ++$i; } ++$n; } @super; } ...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static fin...
my $src = 'unixdict.txt'; open $fh, "<", $src; @words = grep { /^[a-zA-Z]+$/ } <$fh>; map { tr/A-Z/a-z/ } @words; map { tr/abcdefghijklmnopqrstuvwxyz/22233344455566677778889999/ } @dials = @words; @dials = grep {!$h{$_}++} @dials; @textonyms = grep { $h{$_} > 1 } @dials; print "There are @{[scalar @words]} words...
Write a version of this Java function in Perl with identical behavior.
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...
use 5.020; use feature qw<signatures>; no warnings qw<experimental::signatures>; use constant zero => sub ($f) { sub ($x) { $x }}; use constant succ => sub ($n) { sub ($f) { sub ($x) { $f->($n->($f)($x)) }}}; use constant add => sub ($n) { ...
Write a version of this Java function in Perl with identical behavior.
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...
use 5.020; use feature qw<signatures>; no warnings qw<experimental::signatures>; use constant zero => sub ($f) { sub ($x) { $x }}; use constant succ => sub ($n) { sub ($f) { sub ($x) { $f->($n->($f)($x)) }}}; use constant add => sub ($n) { ...
Please provide an equivalent version of this Java code in Perl.
import java.lang.reflect.Method; public class ListMethods { public int examplePublicInstanceMethod(char c, double d) { return 42; } private boolean examplePrivateInstanceMethod(String s) { return true; } public static void main(String[] args) { Class clazz = ListMethod...
package Nums; use overload ('<=>' => \&compare); sub new { my $self = shift; bless [@_] } sub flip { my @a = @_; 1/$a } sub double { my @a = @_; 2*$a } sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) } my $a = Nums->new(42); print "$_\n" for %{ref ($a)."::" });
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.lang.reflect.Method; class Example { public int foo(int x) { return 42 + x; } } public class Main { public static void main(String[] args) throws Exception { Object example = new Example(); String name = "foo"; Class<?> clazz = example.getClass(); Method meth = clazz.getMethod(na...
package Example; sub new { bless {} } sub foo { my ($self, $x) = @_; return 42 + $x; } package main; my $name = "foo"; print Example->new->$name(5), "\n";
Generate an equivalent Perl version of this Java code.
import java.text.MessageFormat; import java.text.ParseException; public class CanonicalizeCIDR { public static void main(String[] args) { for (String test : TESTS) { try { CIDR cidr = new CIDR(test); System.out.printf("%-18s -> %s\n", test, cidr.toString()); ...
use v5.16; use Socket qw(inet_aton inet_ntoa); if (!@ARGV) { chomp(@ARGV = <>); } for (@ARGV) { my ($dotted, $size) = split m my $binary = sprintf "%032b", unpack('N', inet_aton $dotted); substr($binary, $size) = 0 x (32 - $size); $dotted = inet_ntoa(pack 'B32', $binary); say "$dott...
Port the following code from Java to Perl with equivalent syntax and logic.
import java.text.MessageFormat; import java.text.ParseException; public class CanonicalizeCIDR { public static void main(String[] args) { for (String test : TESTS) { try { CIDR cidr = new CIDR(test); System.out.printf("%-18s -> %s\n", test, cidr.toString()); ...
use v5.16; use Socket qw(inet_aton inet_ntoa); if (!@ARGV) { chomp(@ARGV = <>); } for (@ARGV) { my ($dotted, $size) = split m my $binary = sprintf "%032b", unpack('N', inet_aton $dotted); substr($binary, $size) = 0 x (32 - $size); $dotted = inet_ntoa(pack 'B32', $binary); say "$dott...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.math.BigInteger; public class PrimorialPrimes { final static int sieveLimit = 1550_000; static boolean[] notPrime = sieve(sieveLimit); public static void main(String[] args) { int count = 0; for (int i = 1; i < 1000_000 && count < 20; i++) { BigInteger b = primori...
use ntheory ":all"; my $i = 0; for (1..1e6) { my $n = pn_primorial($_); if (is_prime($n-1) || is_prime($n+1)) { print "$_\n"; last if ++$i >= 20; } }
Convert this Java block to Perl, preserving its control flow and logic.
import java.math.BigInteger; public class CombinationsAndPermutations { public static void main(String[] args) { System.out.println(Double.MAX_VALUE); System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:"); for ( int n = 1 ; n <= 12 ; n++ ) { ...
use strict; use warnings; showoff( "Permutations", \&P, "P", 1 .. 12 ); showoff( "Combinations", \&C, "C", map $_*10, 1..6 ); showoff( "Permutations", \&P_big, "P", 5, 50, 500, 1000, 5000, 15000 ); showoff( "Combinations", \&C_big, "C", map $_*100, 1..10 ); sub showoff { my ($text, $code, $fname, @n) = @_; print "\...
Change the programming language of this snippet from Java to Perl without modifying what it does.
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...
use Math::BigFloat try => "GMP,Pari"; my $digits = shift || 100; print agm_pi($digits), "\n"; sub agm_pi { my $digits = shift; my $acc = $digits + 8; my $HALF = Math::BigFloat->new("0.5"); my ($an, $bn, $tn, $pn) = (Math::BigFloat->bone, $HALF->copy->bsqrt($acc), $HALF->copy->b...
Port the following code from Java to Perl with equivalent syntax and logic.
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...
use Math::BigFloat try => "GMP,Pari"; my $digits = shift || 100; print agm_pi($digits), "\n"; sub agm_pi { my $digits = shift; my $acc = $digits + 8; my $HALF = Math::BigFloat->new("0.5"); my ($an, $bn, $tn, $pn) = (Math::BigFloat->bone, $HALF->copy->bsqrt($acc), $HALF->copy->b...
Port the following code from Java to Perl with equivalent syntax and logic.
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() { ...
use strict; use X11::Protocol; my $X = X11::Protocol->new; my $window = $X->new_rsrc; $X->CreateWindow ($window, $X->root, 'InputOutput', 0, 0, 0,0, 3...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.util.LinkedList; import java.util.List; public class LongPrimes { private static void sieve(int limit, List<Integer> primes) { boolean[] c = new boolean[limit]; for (int i = 0; i < limit; i++) c[i] = false; int p = 3, n = 0; int p2 = p * p; ...
use ntheory qw/divisors powmod is_prime/; sub is_long_prime { my($p) = @_; return 0 unless is_prime($p); for my $d (divisors($p-1)) { return $d+1 == $p if powmod(10, $d, $p) == 1; } 0; } print "Long primes ≤ 500:\n"; print join(' ', grep {is_long_prime($_) } 1 .. 500), "\n\n"; for my $n (...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.math.BigInteger; public class PrimorialNumbers { final static int sieveLimit = 1300_000; static boolean[] notPrime = sieve(sieveLimit); public static void main(String[] args) { for (int i = 0; i < 10; i++) System.out.printf("primorial(%d): %d%n", i, primorial(i)); ...
use ntheory qw(pn_primorial); say "First ten primorials: ", join ", ", map { pn_primorial($_) } 0..9; say "primorial(10^$_) has ".(length pn_primorial(10**$_))." digits" for 1..6;
Maintain the same structure and functionality when rewriting this code in Perl.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class EgyptianFractions { private static BigInteger gcd(BigInteger a, BigInteger b) { if (b.equals(BigInteger.ZERO)) { ...
use strict; use warnings; use bigint; sub isEgyption{ my $nr = int($_[0]); my $de = int($_[1]); if($nr == 0 or $de == 0){ return; } if($de % $nr == 0){ printf "1/" . int($de/$nr); return; } if($nr % $de == 0){ printf $nr/$de; return; } if($nr > $de){ printf int($nr...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class EgyptianFractions { private static BigInteger gcd(BigInteger a, BigInteger b) { if (b.equals(BigInteger.ZERO)) { ...
use strict; use warnings; use bigint; sub isEgyption{ my $nr = int($_[0]); my $de = int($_[1]); if($nr == 0 or $de == 0){ return; } if($de % $nr == 0){ printf "1/" . int($de/$nr); return; } if($nr % $de == 0){ printf $nr/$de; return; } if($nr > $de){ printf int($nr...
Write the same code in Perl as shown below in Java.
import static java.lang.Math.*; import java.util.function.Function; public class Test { final static int N = 5; static double[] lroots = new double[N]; static double[] weight = new double[N]; static double[][] lcoef = new double[N + 1][N + 1]; static void legeCoef() { lcoef[0][0] = lcoef[...
use List::Util qw(sum); use constant pi => 3.14159265; sub legendre_pair { my($n, $x) = @_; if ($n == 1) { return $x, 1 } my ($m1, $m2) = legendre_pair($n - 1, $x); my $u = 1 - 1 / $n; (1 + $u) * $x * $m1 - $u * $m2, $m1; } sub legendre { my($n, $x) = @_; (legendre_pair($n, $x))[0] } sub ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
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) ...
use strict; use warnings; my @grid = 0; my ($w, $h, $len); my $cnt = 0; my @next; my @dir = ([0, -1], [-1, 0], [0, 1], [1, 0]); sub walk { my ($y, $x) = @_; if (!$y || $y == $h || !$x || $x == $w) { $cnt += 2; return; } my $t = $y * ($w + 1) + $x; $grid[$_]++ for $t, $len - $t; for my...
Transform the following Java implementation into Perl, maintaining the same output and logic.
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) ...
use strict; use warnings; my @grid = 0; my ($w, $h, $len); my $cnt = 0; my @next; my @dir = ([0, -1], [-1, 0], [0, 1], [1, 0]); sub walk { my ($y, $x) = @_; if (!$y || $y == $h || !$x || $x == $w) { $cnt += 2; return; } my $t = $y * ($w + 1) + $x; $grid[$_]++ for $t, $len - $t; for my...
Convert this Java snippet to Perl and keep its semantics consistent.
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); ...
use feature 'say'; use ntheory 'is_prime'; sub cuban_primes { my ($n) = @_; my @primes; for (my $k = 1 ; ; ++$k) { my $p = 3 * $k * ($k + 1) + 1; if (is_prime($p)) { push @primes, $p; last if @primes >= $n; } } return @primes; } sub commify { s...
Transform the following Java implementation into Perl, maintaining the same output and logic.
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 = ...
use Imager; my $width = 1000; my $height = 1000; my @points = ( [ $width/2, 0], [ 0, $height-1], [$height-1, $height-1], ); my $img = Imager->new( xsize => $width, ysize => $height, channels => 3, ...
Generate a Perl translation of this Java snippet without changing its computational steps.
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 = ...
use Imager; my $width = 1000; my $height = 1000; my @points = ( [ $width/2, 0], [ 0, $height-1], [$height-1, $height-1], ); my $img = Imager->new( xsize => $width, ysize => $height, channels => 3, ...
Translate this program into Perl but keep the logic exactly as in Java.
import java.util.Arrays; public class GroupStage{ static String[] games = {"12", "13", "14", "23", "24", "34"}; static String results = "000000"; private static boolean nextResult(){ if(results.equals("222222")) return false; int res = Integer.parseInt(results, 3) + 1; result...
use Math::Cartesian::Product; @scoring = (0, 1, 3); push @histo, [(0) x 10] for 1..4; push @aoa, [(0,1,2)] for 1..6; for $results (cartesian {@_} @aoa) { my @s; my @g = ([0,1],[0,2],[0,3],[1,2],[1,3],[2,3]); for (0..$ $r = $results->[$_]; $s[$g[$_][0]] += $scoring[$r]; $s[$g[$_]...
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String ...
my %prec = ( '^' => 4, '*' => 3, '/' => 3, '+' => 2, '-' => 2, '(' => 1 ); my %assoc = ( '^' => 'right', '*' => 'left', '/' => 'left', '+' => 'left', '-' => 'left' ); sub shunting_yard { my @inp = split ' ', $_[0]; my @ops; my @res; my $report = sub { print...
Convert this Java block to Perl, preserving its control flow and logic.
public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255, Z = (int)Math.floor(z) & 255; x -= Math.floor(x); y...
use strict; use warnings; use experimental 'signatures'; use constant permutation => qw{ 151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174...
Produce a functionally identical Perl code for the snippet given in Java.
package astar; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.Comparator; import java.util.LinkedList; import java.util.Queue; class AStar { private final List<Node> open; private final List<Node> closed; private final Lis...
use strict; use warnings; use List::AllUtils qw( nsort_by ); sub distance { my ($r1, $c1, $r2, $c2) = split /[, ]/, "@_"; sqrt( ($r1-$r2)**2 + ($c1-$c2)**2 ); } my $start = '0,0'; my $finish = '7,7'; my %barrier = map {$_, 100} split ' ', '2,4 2,5 2,6 3,6 4,6 5,6 5,5 5,4 5,3 5,2 4,2 3,2'; my %values = ( ...
Port the following code from Java to Perl with equivalent syntax and logic.
package astar; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.Comparator; import java.util.LinkedList; import java.util.Queue; class AStar { private final List<Node> open; private final List<Node> closed; private final Lis...
use strict; use warnings; use List::AllUtils qw( nsort_by ); sub distance { my ($r1, $c1, $r2, $c2) = split /[, ]/, "@_"; sqrt( ($r1-$r2)**2 + ($c1-$c2)**2 ); } my $start = '0,0'; my $finish = '7,7'; my %barrier = map {$_, 100} split ' ', '2,4 2,5 2,6 3,6 4,6 5,6 5,5 5,4 5,3 5,2 4,2 3,2'; my %values = ( ...
Change the following Java code into Perl without altering its purpose.
import java.util.*; import static java.util.Arrays.*; import static java.util.stream.Collectors.toList; public class NonogramSolver { static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}; static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE " + "CD AE A DA BBB CC...
use strict; use warnings; my $file = 'nonogram_problems.txt'; open my $fd, '<', $file or die "$! opening $file"; while(my $row = <$fd> ) { $row =~ /\S/ or next; my $column = <$fd>; my @rpats = makepatterns($row); my @cpats = makepatterns($column); my @rows = ( '.' x @cpats ) x @rpats; for( my $prev = ''...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.*; import static java.util.Arrays.*; import static java.util.stream.Collectors.toList; public class NonogramSolver { static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}; static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE " + "CD AE A DA BBB CC...
use strict; use warnings; my $file = 'nonogram_problems.txt'; open my $fd, '<', $file or die "$! opening $file"; while(my $row = <$fd> ) { $row =~ /\S/ or next; my $column = <$fd>; my @rpats = makepatterns($row); my @cpats = makepatterns($column); my @rows = ( '.' x @cpats ) x @rpats; for( my $prev = ''...
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } ...
use strict; use warnings; use English; use Const::Fast; use Math::AnyNum qw(:overload); const my $n_max => 10_000; const my $iter_cutoff => 500; my(@seq_dump, @seed_lychrels, @related_lychrels); for (my $n=1; $n<=$n_max; $n++) { my @seq = lychrel_sequence($n); if ($iter_cutoff == scalar @seq) { ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } ...
use strict; use warnings; use English; use Const::Fast; use Math::AnyNum qw(:overload); const my $n_max => 10_000; const my $iter_cutoff => 500; my(@seq_dump, @seed_lychrels, @related_lychrels); for (my $n=1; $n<=$n_max; $n++) { my @seq = lychrel_sequence($n); if ($iter_cutoff == scalar @seq) { ...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FIL...
use Math::BigRat try=>"GMP"; sub taneval { my($coef,$f) = @_; $f = Math::BigRat->new($f) unless ref($f); return 0 if $coef == 0; return $f if $coef == 1; return -taneval(-$coef, $f) if $coef < 0; my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) ); ($a+$b)/(1-$a*$b); } sub tans { my @x...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FIL...
use Math::BigRat try=>"GMP"; sub taneval { my($coef,$f) = @_; $f = Math::BigRat->new($f) unless ref($f); return 0 if $coef == 0; return $f if $coef == 1; return -taneval(-$coef, $f) if $coef < 0; my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) ); ($a+$b)/(1-$a*$b); } sub tans { my @x...
Port the provided Java code into Perl while preserving the original functionality.
import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Random; public class IsaacRandom extends Random { private static final long serialVersionUID = 1L; private final int[] randResult = new int[256]; private int valuesUsed; private final int[...
use warnings; use strict; use Math::Random::ISAAC; my $message = "a Top Secret secret"; my $key = "this is my secret key"; my $enc = xor_isaac($key, $message); my $dec = xor_isaac($key, join "", pack "H*", $enc); print "Message: $message\n"; print "Key  : $key\n"; print "XOR  : $enc\n"; print "XOR dcr: ", join("...
Write the same algorithm in Perl as shown in this Java implementation.
import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Random; public class IsaacRandom extends Random { private static final long serialVersionUID = 1L; private final int[] randResult = new int[256]; private int valuesUsed; private final int[...
use warnings; use strict; use Math::Random::ISAAC; my $message = "a Top Secret secret"; my $key = "this is my secret key"; my $enc = xor_isaac($key, $message); my $dec = xor_isaac($key, join "", pack "H*", $enc); print "Message: $message\n"; print "Key  : $key\n"; print "XOR  : $enc\n"; print "XOR dcr: ", join("...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.val...
use ntheory qw/:all/; my $n = 3; print " Iterate Lexicographic rank/unrank of $n objects\n"; for my $k (0 .. factorial($n)-1) { my @perm = numtoperm($n, $k); my $rank = permtonum(\@perm); die unless $rank == $k; printf "%2d --> [@perm] --> %2d\n", $k, $rank; } print "\n"; print " Four 12-object random p...
Keep all operations the same but rewrite the snippet in Perl.
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.val...
use ntheory qw/:all/; my $n = 3; print " Iterate Lexicographic rank/unrank of $n objects\n"; for my $k (0 .. factorial($n)-1) { my @perm = numtoperm($n, $k); my $rank = permtonum(\@perm); die unless $rank == $k; printf "%2d --> [@perm] --> %2d\n", $k, $rank; } print "\n"; print " Four 12-object random p...
Preserve the algorithm and functionality while converting the code from Java to Perl.
public class FirstPowerOfTwo { public static void main(String[] args) { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(123, 678910); } private static void runTest(int l, int n) { System.out.printf("p(%d, %d) = %,d%n", l, n...
use strict; use warnings; use feature 'say'; use feature 'state'; use POSIX qw(fmod); use Perl6::GatherTake; use constant ln2ln10 => log(2) / log(10); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub ordinal_digit { my($d) = $_[0] =~ /(.)$/; $d eq '1' ? 'st' : $d eq '2' ? 'nd' : $d ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
public class FirstPowerOfTwo { public static void main(String[] args) { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(123, 678910); } private static void runTest(int l, int n) { System.out.printf("p(%d, %d) = %,d%n", l, n...
use strict; use warnings; use feature 'say'; use feature 'state'; use POSIX qw(fmod); use Perl6::GatherTake; use constant ln2ln10 => log(2) / log(10); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub ordinal_digit { my($d) = $_[0] =~ /(.)$/; $d eq '1' ? 'st' : $d eq '2' ? 'nd' : $d ...
Produce a functionally identical Perl code for the snippet given in Java.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= ...
use strict; use warnings; use bigint; use feature 'say'; use feature 'state'; no warnings 'recursion'; use List::Util qw(max); sub Stirling2 { my($n, $k) = @_; my $n1 = $n - 1; return 1 if $n1 == $k; return 0 unless $n1 && $k; state %seen; return ($seen{"{$n1}|{$k}" } //= Stirling2($n1,$k ...
Port the provided Java code into Perl while preserving the original functionality.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= ...
use strict; use warnings; use bigint; use feature 'say'; use feature 'state'; no warnings 'recursion'; use List::Util qw(max); sub Stirling2 { my($n, $k) = @_; my $n1 = $n - 1; return 1 if $n1 == $k; return 0 unless $n1 && $k; state %seen; return ($seen{"{$n1}|{$k}" } //= Stirling2($n1,$k ...
Please provide an equivalent version of this Java code in Perl.
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static...
use bigint; use ntheory qw(is_prime); sub Legendre { my($n,$p) = @_; return -1 unless $p != 2 && is_prime($p); my $x = ($n->as_int())->bmodpow(int(($p-1)/2), $p); if ($x==0) { return 0 } elsif ($x==1) { return 1 } else { return -1 } } sub Cipolla { my($n, $p) = @_; retur...
Change the following Java code into Perl without altering its purpose.
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static...
use bigint; use ntheory qw(is_prime); sub Legendre { my($n,$p) = @_; return -1 unless $p != 2 && is_prime($p); my $x = ($n->as_int())->bmodpow(int(($p-1)/2), $p); if ($x==0) { return 0 } elsif ($x==1) { return 1 } else { return -1 } } sub Cipolla { my($n, $p) = @_; retur...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PierpontPrimes { public static void main(String[] args) { NumberFormat nf = NumberFormat.getNumberInstance(); display("First 50 Pierpont primes of the first kind:", pierpontP...
use strict; use warnings; use feature 'say'; use bigint try=>"GMP"; use ntheory qw<is_prime>; sub min_index { my $b = $_[my $i = 0]; $_[$_] < $b && ($b = $_[$i = $_]) for 0..$ sub iter1 { my $m = shift; my $e = 0; return sub { $m ** $e++; } } sub iter2 { my $m = shift; my $e = 1; return sub { $m * ($e *= 2) } } ...
Keep all operations the same but rewrite the snippet in Perl.
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class NSmoothNumbers { public static void main(String[] args) { System.out.printf("show the first 25 n-smooth numbers for n = 2 through n = 29%n"); int max = 25; List<BigInteger> primes = new ArrayList<>...
use strict; use warnings; use feature 'say'; use ntheory qw<primes>; use List::Util qw<min>; use Math::GMPz; sub smooth_numbers { my @m = map { Math::GMPz->new($_) } @_; my @s; push @s, [1] for 0..$ return sub { my $n = $s[0][0]; $n = min $n, $s[$_][0] for 1..$ for (0..$ ...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.util.Arrays; import java.util.stream.IntStream; public class PartitionInteger { private static final int[] primes = IntStream.concat(IntStream.of(2), IntStream.iterate(3, n -> n + 2)) .filter(PartitionInteger::isPrime) .limit(50_000) .toArray(); private static boolean isPri...
use ntheory ":all"; sub prime_partition { my($num, $parts) = @_; return is_prime($num) ? [$num] : undef if $parts == 1; my @p = @{primes($num)}; my $r; forcomb { lastfor, $r = [@p[@_]] if vecsum(@p[@_]) == $num; } @p, $parts; $r; } foreach my $test ([18,2], [19,3], [20,4], [99807,1], [99809,1], [2017,24],...
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.List; public class Zeckendorf implements Comparable<Zeckendorf> { private static List<String> dig = List.of("00", "01", "10"); private static List<String> dig1 = List.of("", "1", "10"); private String x; private int dVal = 0; private int dLen = 0; public Zeckendorf() { ...
use v5.36; package Zeckendorf; use overload qw("" zstring + zadd - zsub ++ zinc -- zdec * zmul / zdiv ge zge); sub new ($class, $value) { bless \$value, ref $class || $class; } sub zinc ($self, $, $) { local $_ = $$self; s/0$/1/ or s/(?:^|0)1$/10/; 1 while s/(?:^|0)11/100/; $$self = $self->new( s...
Generate an equivalent Perl version of this Java code.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersFirstKind { public static void main(String[] args) { System.out.println("Unsigned Stirling numbers of the first kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ...
use strict; use warnings; use bigint; use feature 'say'; use feature 'state'; no warnings 'recursion'; use List::Util qw(max); sub Stirling1 { my($n, $k) = @_; return 1 unless $n || $k; return 0 unless $n && $k; state %seen; return ($seen{"{$n-1}|{$k-1}"} //= Stirling1($n-1, $k-1)) + ($s...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersFirstKind { public static void main(String[] args) { System.out.println("Unsigned Stirling numbers of the first kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ...
use strict; use warnings; use bigint; use feature 'say'; use feature 'state'; no warnings 'recursion'; use List::Util qw(max); sub Stirling1 { my($n, $k) = @_; return 1 unless $n || $k; return 0 unless $n && $k; state %seen; return ($seen{"{$n-1}|{$k-1}"} //= Stirling1($n-1, $k-1)) + ($s...