Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in Perl.
import javafx.util.Pair; import java.util.ArrayList; import java.util.List; public class LineSimplification { private static class Point extends Pair<Double, Double> { Point(Double key, Double value) { super(key, value); } @Override public String toString() { ...
use strict; use warnings; use feature 'say'; use List::MoreUtils qw(firstidx minmax); my $epsilon = 1; sub norm { my(@list) = @_; my $sum; $sum += $_**2 for @list; sqrt($sum) } sub perpendicular_distance { our(@start,@end,@point); local(*start,*end,*point) = (shift, shift, shift); return ...
Translate this program into Perl but keep the logic exactly as in Java.
import javafx.util.Pair; import java.util.ArrayList; import java.util.List; public class LineSimplification { private static class Point extends Pair<Double, Double> { Point(Double key, Double value) { super(key, value); } @Override public String toString() { ...
use strict; use warnings; use feature 'say'; use List::MoreUtils qw(firstidx minmax); my $epsilon = 1; sub norm { my(@list) = @_; my $sum; $sum += $_**2 for @list; sqrt($sum) } sub perpendicular_distance { our(@start,@end,@point); local(*start,*end,*point) = (shift, shift, shift); return ...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class BilinearInterpolation { private static int get(int self, int n) { return (self >> (n * 8)) & 0xFF; } private static float lerp(float s, float e, float t) { ...
use strict; use warnings; use GD; my $image = GD::Image->newFromPng('color_wheel.png'); $image->interpolationMethod( ['GD_BILINEAR_FIXED'] ); my($width,$height) = $image->getBounds(); my $image2 = $image->copyScaleInterpolated( 1.6*$width, 1.6*$height ); $image2->_file('color_wheel_interpolated.png');
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class BilinearInterpolation { private static int get(int self, int n) { return (self >> (n * 8)) & 0xFF; } private static float lerp(float s, float e, float t) { ...
use strict; use warnings; use GD; my $image = GD::Image->newFromPng('color_wheel.png'); $image->interpolationMethod( ['GD_BILINEAR_FIXED'] ); my($width,$height) = $image->getBounds(); my $image2 = $image->copyScaleInterpolated( 1.6*$width, 1.6*$height ); $image2->_file('color_wheel_interpolated.png');
Port the following code from Java to Perl with equivalent syntax and logic.
import java.util.Locale; public class Test { public static void main(String[] args) { System.out.println(new Vec2(5, 7).add(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).mult(11)); System.out.println(new Vec2(5, 7).div(2...
use v5.36; package Vector; use Moose; use overload '+' => \&add, '-' => \&sub, '*' => \&mul, '/' => \&div, '""' => \&stringify; has 'x' => (is =>'rw', isa => 'Num', required => 1); has 'y' => (is =>'rw', isa => 'Num', required => 1); sub add ($a, $b, $) { Vecto...
Convert this Java snippet to Perl and keep its semantics consistent.
import static java.lang.Math.*; import java.util.Locale; public class Test { public static void main(String[] args) { Pt a = Pt.fromY(1); Pt b = Pt.fromY(2); System.out.printf("a = %s%n", a); System.out.printf("b = %s%n", b); Pt c = a.plus(b); System.out.printf("c =...
package EC; { our ($A, $B) = (0, 7); package EC::Point; sub new { my $class = shift; bless [ @_ ], $class } sub zero { bless [], shift } sub x { shift->[0] }; sub y { shift->[1] }; sub double { my $self = shift; return $self unless @$self; my $L = (3 * $self->x**2) / (2*$...
Please provide an equivalent version of this Java code in Perl.
import static java.lang.Math.*; import java.util.Locale; public class Test { public static void main(String[] args) { Pt a = Pt.fromY(1); Pt b = Pt.fromY(2); System.out.printf("a = %s%n", a); System.out.printf("b = %s%n", b); Pt c = a.plus(b); System.out.printf("c =...
package EC; { our ($A, $B) = (0, 7); package EC::Point; sub new { my $class = shift; bless [ @_ ], $class } sub zero { bless [], shift } sub x { shift->[0] }; sub y { shift->[1] }; sub double { my $self = shift; return $self unless @$self; my $L = (3 * $self->x**2) / (2*$...
Change the following Java code into Perl without altering its purpose.
import static java.lang.Math.*; import java.util.function.Function; public class ChebyshevCoefficients { static double map(double x, double min_x, double max_x, double min_to, double max_to) { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to; } static void chebyshevCo...
use constant PI => 2 * atan2(1, 0); sub chebft { my($func, $a, $b, $n) = @_; my($bma, $bpa) = ( 0.5*($b-$a), 0.5*($b+$a) ); my @pin = map { ($_ + 0.5) * (PI/$n) } 0..$n-1; my @f = map { $func->( cos($_) * $bma + $bpa ) } @pin; my @c = (0) x $n; for my $j (0 .. $n-1) { $c[$j] += $f[$_] * cos($j *...
Write a version of this Java function in Perl with identical behavior.
import java.util.ArrayList; import java.util.List; public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003"; private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String canno...
use utf8; binmode STDOUT, ":utf8"; use constant STX => '👍 '; sub transform { my($s) = @_; my($t); warn "String can't contain STX character." and exit if $s =~ /STX/; $s = STX . $s; $t .= substr($_,-1,1) for sort map { rotate($s,$_) } 1..length($s); return $t; } sub rotate { my($s,$n) = @_; j...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.util.ArrayList; import java.util.List; public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003"; private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String canno...
use utf8; binmode STDOUT, ":utf8"; use constant STX => '👍 '; sub transform { my($s) = @_; my($t); warn "String can't contain STX character." and exit if $s =~ /STX/; $s = STX . $s; $t .= substr($_,-1,1) for sort map { rotate($s,$_) } 1..length($s); return $t; } sub rotate { my($s,$n) = @_; j...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; public class CardShuffles{ private static final Random rand = new Random(); public static <T> LinkedList<T> riffleShuffle(List<T> list, int flips){ LinkedList<T> newList = new Linke...
sub overhand { our @cards; local *cards = shift; my(@splits,@shuffle); my $x = int +@cards / 5; push @splits, (1..$x)[int rand $x] for 1..+@cards; while (@cards) { push @shuffle, [splice @cards, 0, shift @splits]; } @cards = flatten(reverse @shuffle); } sub flatten { map { ref $_ eq...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; public class CardShuffles{ private static final Random rand = new Random(); public static <T> LinkedList<T> riffleShuffle(List<T> list, int flips){ LinkedList<T> newList = new Linke...
sub overhand { our @cards; local *cards = shift; my(@splits,@shuffle); my $x = int +@cards / 5; push @splits, (1..$x)[int rand $x] for 1..+@cards; while (@cards) { push @shuffle, [splice @cards, 0, shift @splits]; } @cards = flatten(reverse @shuffle); } sub flatten { map { ref $_ eq...
Keep all operations the same but rewrite the snippet in Perl.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream; public class FaulhabersTriangle { private static final MathContext MC = new MathContext(256); private static long gcd(long a, long b) { if (b == 0) { return a; } ...
use 5.010; use List::Util qw(sum); use Math::BigRat try => 'GMP'; use ntheory qw(binomial bernfrac); sub faulhaber_triangle { my ($p) = @_; map { Math::BigRat->new(bernfrac($_)) * binomial($p, $_) / $p } reverse(0 .. $p-1); } foreach my $p (1 .. 10) { say map { sprintf("%6...
Produce a functionally identical Perl code for the snippet given in Java.
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; st...
use Math::GMPz; my $nmax = 250; my $nbranches = 4; my @rooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @unrooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @c = map { Math::GMPz->new(0) } 0 .. $nbranches-1; sub tree { my($br, $n, $l, $sum, $cnt) = @_; for my $b ($br+1 .. $nbranches) { ...
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; st...
use Math::GMPz; my $nmax = 250; my $nbranches = 4; my @rooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @unrooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @c = map { Math::GMPz->new(0) } 0 .. $nbranches-1; sub tree { my($br, $n, $l, $sum, $cnt) = @_; for my $b ($br+1 .. $nbranches) { ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD",...
sub no_suffix { my($name) = @_; $name =~ s/\h([JS]R)|([IVX]+)$//i; return uc $name; } sub nysiis { my($name) = @_; local($_) = uc $name; s/[^A-Z]//g; s/^MAC/MCC/; s/^P[FH]/FF/; s/^SCH/SSS/; s/^KN/N/; s/[IE]E$/Y/; s/[DRN]T$/D/; s/[RN]D$/D/; s/(.)EV/$1AF/g; s/...
Write a version of this Java function in Perl with identical behavior.
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD",...
sub no_suffix { my($name) = @_; $name =~ s/\h([JS]R)|([IVX]+)$//i; return uc $name; } sub nysiis { my($name) = @_; local($_) = uc $name; s/[^A-Z]//g; s/^MAC/MCC/; s/^P[FH]/FF/; s/^SCH/SSS/; s/^KN/N/; s/[IE]E$/Y/; s/[DRN]T$/D/; s/[RN]D$/D/; s/(.)EV/$1AF/g; s/...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.util.Arrays; import java.util.stream.IntStream; public class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static class Frac implements Comparable<Frac> { private long num; ...
use 5.014; use Math::Algebra::Symbols; sub bernoulli_number { my ($n) = @_; return 0 if $n > 1 && $n % 2; my @A; for my $m (0 .. $n) { $A[$m] = symbols(1) / ($m + 1); for (my $j = $m ; $j > 0 ; $j--) { $A[$j - 1] = $j * ($A[$j - 1] - $A[$j]); } } return $...
Translate this program into Perl but keep the logic exactly as in Java.
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.m...
use strict; use warnings; use Net::LDAP; my $ldap = Net::LDAP->new( 'ldap://ldap.forumsys.com' ) or die "$@"; my $mesg = $ldap->bind( "cn=read-only-admin,dc=example,dc=com", password => "password" ); $mesg->code and die $mesg->error; my $srch = $ldap->sear...
Write the same algorithm in Perl as shown in this Java implementation.
public class PrimeConspiracy { public static void main(String[] args) { final int limit = 1000_000; final int sieveLimit = 15_500_000; int[][] buckets = new int[10][10]; int prevDigit = 2; boolean[] notPrime = sieve(sieveLimit); for (int n = 3, primeCount = 1; prim...
use ntheory qw/forprimes nth_prime/; my $upto = 1_000_000; my %freq; my($this_digit,$last_digit)=(2,0); forprimes { ($last_digit,$this_digit) = ($this_digit, $_ % 10); $freq{$last_digit . $this_digit}++; } 3,nth_prime($upto); print "$upto first primes. Transitions prime % 10 → next-prime % 10.\n"; printf "%s → ...
Write a version of this Java function in Perl with identical behavior.
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET....
use strict; use warnings; use feature 'say'; sub bagchain { my($x, $n, $bb, $start) = @_; return [@$x] unless $n; my @sets; $start //= 0; for my $i ($start .. @$bb-1) { my($c, $s) = @{$$bb[$i]}; push @sets, bagchain([$$x[0] + $c, $$x[1] . $s], $n-$c, $bb, $i) if $c <= $n } ...
Translate the given Java code snippet into Perl without altering its behavior.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LuckyNumbers { private static int MAX = 200000; private static List<Integer> luckyEven = luckyNumbers(MAX, true); private static List<Integer> luckyOdd = luckyNumbers(MAX, false); public static void main...
use Perl6::GatherTake; sub luck { my($a,$b) = @_; gather { my $i = $b; my(@taken,@rotor,$j); take 0; push @taken, take $a; while () { for ($j = 0; $j < @rotor; $j++) { --$rotor[$j] or last; } if ($j < @rotor) { $rotor[$j] = $taken[$j+1]; }...
Write the same algorithm in Perl as shown in this Java implementation.
public class ImaginaryBaseNumber { private static class Complex { private Double real, imag; public Complex(double r, double i) { this.real = r; this.imag = i; } public Complex(int r, int i) { this.real = (double) r; this.imag = (doub...
use strict; use warnings; use feature 'say'; use Math::Complex; use List::AllUtils qw(sum mesh); use ntheory qw<todigitstring fromdigits>; sub zip { my($a,$b) = @_; my($la, $lb) = (length $a, length $b); my $l = '0' x abs $la - $lb; $a .= $l if $la < $lb; $b .= $l if $lb < $la; (join('', mesh(...
Maintain the same structure and functionality when rewriting this code in Perl.
import static java.lang.Math.*; import static java.util.Arrays.stream; import java.util.Locale; import java.util.function.DoubleSupplier; import static java.util.stream.Collectors.joining; import java.util.stream.DoubleStream; import static java.util.stream.IntStream.range; public class Test implements DoubleSupplier ...
use constant pi => 3.14159265; use List::Util qw(sum reduce min max); sub normdist { my($m, $sigma) = @_; my $r = sqrt -2 * log rand; my $theta = 2 * pi * rand; $r * cos($theta) * $sigma + $m; } $size = 100000; $mean = 50; $stddev = 4; push @dataset, normdist($mean,$stddev) for 1..$size; my $m = sum...
Translate the given Java code snippet into Perl without altering its behavior.
import java.util.Arrays; import static java.util.Arrays.stream; import java.util.concurrent.*; public class VogelsApproximationMethod { final static int[] demand = {30, 20, 70, 30, 60}; final static int[] supply = {50, 60, 50, 50}; final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, ...
use strict; use warnings; use List::AllUtils qw( max_by nsort_by min ); my $data = <<END; A=30 B=20 C=70 D=30 E=60 W=50 X=60 Y=50 Z=50 AW=16 BW=16 CW=13 DW=22 EW=17 AX=14 BX=14 CX=13 DX=19 EX=15 AY=19 BY=19 CY=20 DY=23 EY=50 AZ=50 BZ=12 CZ=50 DZ=15 EZ=11 END my $table = sprintf +('%4s' x 6 . "\n") x 5, map {my $t...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class MinimumNumberOnlyZeroAndOne { public static void main(String[] args) { for ( int n : getTestCases() ) { BigInteger result = getA004290(n); System.out.printf("A004290(%d) = %s = %s * %s%n"...
use strict; use warnings; use Math::AnyNum qw(:overload as_bin digits2num); for my $x (1..10, 95..105, 297, 576, 594, 891, 909, 999) { my $y; if ($x =~ /^9+$/) { $y = digits2num([(1) x (9 * length $x)],2) } else { while (1) { last unless as_bin(++$y) % $x } } printf "%4d: %28s %s\n", $x...
Convert this Java block to Perl, preserving its control flow and logic.
import java.util.ArrayList; import java.util.List; public class WeirdNumbers { public static void main(String[] args) { int n = 2; for ( int count = 1 ; count <= 25 ; n += 2 ) { if ( isWeird(n) ) { System.out.printf("w(%d) = %d%n", count, n); co...
use strict; use feature 'say'; use List::Util 'sum'; use POSIX 'floor'; use Algorithm::Combinatorics 'subsets'; use ntheory <is_prime divisors>; sub abundant { my($x) = @_; my $s = sum( my @l = is_prime($x) ? 1 : grep { $x != $_ } divisors($x) ); $s > $x ? ($s, sort { $b <=> $a } @l) : (); } my(@weird,$n...
Generate an equivalent Perl version of this Java code.
import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID ...
use strict; use warnings; $_ = <<END; +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ...
Change the following Java code into Perl without altering its purpose.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Peaceful { enum Piece { Empty, Black, White, } public static class Position { public int x, y; public Position(int x, int y) { this.x = x; this.y = y; ...
use strict; use warnings; my $m = shift // 4; my $n = shift // 5; my %seen; my $gaps = join '|', qr/-*/, map qr/.{$_}(?:-.{$_})*/s, $n-1, $n, $n+1; my $attack = qr/(\w)(?:$gaps)(?!\1)\w/; place( scalar ('-' x $n . "\n") x $n ); print "No solution to $m $n\n"; sub place { local $_ = shift; $seen{$_}++ || /$atta...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class SequenceNthNumberWithExactlyNDivisors { public static void main(String[] args) { int max = 45; smallPrimes(max); for ( int n = 1; n <= max ; n++ ) { System.out.printf("A073916(%d) = %s%...
use strict; use warnings; use bigint; use ntheory <nth_prime is_prime divisors>; my $limit = 20; print "First $limit terms of OEIS:A073916\n"; for my $n (1..$limit) { if ($n > 4 and is_prime($n)) { print nth_prime($n)**($n-1) . ' '; } else { my $i = my $x = 0; while (1) { ...
Produce a functionally identical Perl code for the snippet given in Java.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class NBodySim { private static class Vector3D { double x, y, z; public Vector3D(double x, double y, double z) { this.x ...
use strict; use warnings; use constant PI => 3.141592653589793; use constant SOLAR_MASS => (4 * PI * PI); use constant YEAR => 365.24; sub solar_offset { my($vxs, $vys, $vzs, $mass) = @_; my($px, $py, $pz); for (0..@$mass-1) { $px += @$vxs[$_] * @$mass[$_]; $py += @$vys[$_] *...
Write a version of this Java function in Perl with identical behavior.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; public class ReadlineInterface { private static LinkedList<String> histArr = new LinkedList<>(); private static void hist() { if (hi...
use strict; use warnings; use Term::ReadLine; use POSIX; my $term = Term::ReadLine->new( 'simple Perl shell' ); my $attribs = $term->Attribs; $attribs->{completion_append_character} = ' '; $attribs->{attempted_completion_function} = \&attempt_perl_completion; $attribs->{completion_display_matches_hook} = \&perl_...
Change the following Java code into Perl without altering its purpose.
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.ArrayList; import java.util.regex.Pattern; public class TasksWithoutExamples { priva...
use strict; use warnings; use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $html = $ua->request( HTTP::Request->new( GET => 'http://rosettacode.org/wiki/Category:Programming_Tasks'))->content; my @tasks = $html =~ m for my $title (@tasks) { my $html = $ua->request( HTTP::Request->new( GET => "http://roset...
Write the same code in Perl as shown below in Java.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class Processing { private static class UserInput { private...
use strict; use warnings; use feature 'say'; use feature 'state'; use ntheory qw/fromdigits todigitstring/; my $key = 'perl5'; srand fromdigits($key,36) % 2**63; my @stream; sub stream { my($i) = shift; state @chars; push @chars, chr($_) for 14..127; $stream[$i] = $chars[rand 1+127-14] unless $strea...
Write the same code in Perl as shown below in Java.
import java.util.Objects; public class PrintDebugStatement { private static void printDebug(String message) { Objects.requireNonNull(message); RuntimeException exception = new RuntimeException(); StackTraceElement[] stackTrace = exception.getStackTrace(); Sta...
use Carp; $str = 'Resistance'; carp "'$str' is futile."; print "\n"; doodle($str); print "\n"; fiddle(7); sub doodle { my ($str) = @_; carp "'$str' is still futile." } sub fiddle { faddle(2*shift) } sub faddle { fuddle(3*shift) } sub fuddle { ( carp("'$_[0]', interesting number.") ); }
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.math.BigInteger; public class MontgomeryReduction { private static final BigInteger ZERO = BigInteger.ZERO; private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TWO = BigInteger.valueOf(2); public static class Montgomery { public static final int BA...
use bigint; use ntheory qw(powmod); sub msb { my ($n, $base) = (shift, 0); $base++ while $n >>= 1; $base; } sub montgomery_reduce { my($m, $a) = @_; for (0 .. msb($m)) { $a += $m if $a & 1; $a >>= 1 } $a % $m } my $m = 750791094644726559640638407699; my $t1 = 323165824550862327...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.*; public class FiniteStateMachine { private enum State { Ready(true, "Deposit", "Quit"), Waiting(true, "Select", "Refund"), Dispensing(true, "Remove"), Refunding(false, "Refunding"), Exiting(false, "Quiting"); State(boolean exp, String... in) { ...
use strict; use warnings; my ($state, $action, %fsm) = 'ready'; while( <DATA> ) { my ($start, $action, $end, $message) = split ' ', $_, 4; $fsm{$start}{$action} = { next => $end, message => $message || "\n" }; } while( $state ne 'exit' ) { print "in state $state\n"; do { ($action) = grep $_ e...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.util.*; public class Sokoban { String destBoard, currBoard; int playerX, playerY, nCols; Sokoban(String[] board) { nCols = board[0].length(); StringBuilder destBuf = new StringBuilder(); StringBuilder currBuf = new StringBuilder(); for (int r = 0; r < board.len...
use strict; use warnings qw(FATAL all); my @initial = split /\n/, <<''; =for space is an empty square @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal =cut my $cols = length($initial[0]); my $initial = join '', @initial; my $size = length($initial); die unless $si...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ZumkellerNumbers { public static void main(String[] args) { int n = 1; System.out.printf("First 220 Zumkeller numbers:%n"); for ( int count = 1 ; count <= 220 ; n += 1 ) { if ( isZumke...
use strict; use warnings; use feature 'say'; use ntheory <is_prime divisor_sum divisors vecsum forcomb lastfor>; sub in_columns { my($columns, $values) = @_; my @v = split ' ', $values; my $width = int(80/$columns); printf "%${width}d"x$columns."\n", @v[$_*$columns .. -1+(1+$_)*$columns] for 0..-1+@v/$...
Write the same code in Perl as shown below in Java.
import java.io.File; import java.util.*; import java.util.regex.*; public class CommatizingNumbers { public static void main(String[] args) throws Exception { commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " "); commatize("The author...
@input = ( ['pi=3.14159265358979323846264338327950288419716939937510582097494459231', ' ', 5], ['The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', '.'], ['-in Aus$+1411.8millions'], ['===US$0017440 millions=== (in 2000 dollars)'], ['123.e8000 is pretty big.'], ['The land area...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class RareNumbers { ...
use strict; use warnings; use integer; my $count = 0; my @squares; for my $large ( 0 .. 1e5 ) { my $largesquared = $squares[$large] = $large * $large; for my $small ( 0 .. $large - 1 ) { my $n = $largesquared + $squares[$small]; 2 * $large * $small == reverse $n or next; printf "%12s %s\n", $...
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.util.ArrayList; import java.util.List; public class SuffixTreeProblem { private static class Node { String sub = ""; List<Integer> ch = new ArrayList<>(); } private static class SuffixTree { private List<Node> nodes = new ArrayList<>(); ...
use strict; use warnings; use Data::Dumper; sub classify { my $h = {}; for (@_) { push @{$h->{substr($_,0,1)}}, $_ } return $h; } sub suffixes { my $str = shift; map { substr $str, $_ } 0 .. length($str) - 1; } sub suffix_tree { return +{} if @_ == 0; return +{ $_[0] => +{} } if @_ == 1; ...
Convert this Java block to Perl, preserving its control flow and logic.
import java.util.ArrayList; import java.util.List; public class SuffixTreeProblem { private static class Node { String sub = ""; List<Integer> ch = new ArrayList<>(); } private static class SuffixTree { private List<Node> nodes = new ArrayList<>(); ...
use strict; use warnings; use Data::Dumper; sub classify { my $h = {}; for (@_) { push @{$h->{substr($_,0,1)}}, $_ } return $h; } sub suffixes { my $str = shift; map { substr $str, $_ } 0 .. length($str) - 1; } sub suffix_tree { return +{} if @_ == 0; return +{ $_[0] => +{} } if @_ == 1; ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); Sys...
{ package Point; use Class::Spiffy -base; field 'x'; field 'y'; } { package Circle; use base qw(Point); field 'r'; } my $p1 = Point->new(x => 8, y => -5); my $c1 = Circle->new(r => 4); my $c2 = Circle->new(x => 1, y => 2, r => 3); use Data::Dumper; say Dumper $p1; say Dumper $c1; ...
Please provide an equivalent version of this Java code in Perl.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Eertree { public static void main(String[] args) { List<Node> tree = eertree("eertree"); List<String> result = subPalindromes(tree); System.out.println(result); } private...
$str = "eertree"; for $n (1 .. length($str)) { for $m (1 .. length($str)) { $strrev = ""; $strpal = substr($str, $n-1, $m); if ($strpal ne "") { for $p (reverse 1 .. length($strpal)) { $strrev .= substr($strpal, $p-1, 1); } ($strpal eq $strrev) and push @pal,...
Convert this Java block to Perl, preserving its control flow and logic.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Eertree { public static void main(String[] args) { List<Node> tree = eertree("eertree"); List<String> result = subPalindromes(tree); System.out.println(result); } private...
$str = "eertree"; for $n (1 .. length($str)) { for $m (1 .. length($str)) { $strrev = ""; $strpal = substr($str, $n-1, $m); if ($strpal ne "") { for $p (reverse 1 .. length($strpal)) { $strrev .= substr($strpal, $p-1, 1); } ($strpal eq $strrev) and push @pal,...
Write a version of this Java function in Perl with identical behavior.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58);...
use Math::BigInt; sub encode_base58 { my ($num) = @_; $num = Math::BigInt->new($num); my $chars = [qw( 1 2 3 4 5 6 7 8 9 A B C D E F G H J K L M N P Q R S T U V W X Y Z a b c d e f g h i j k m n o p q r s t u v w x y z )]; my $base58; while ($num->is_pos) { my ($quot...
Please provide an equivalent version of this Java code in Perl.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58);...
use Math::BigInt; sub encode_base58 { my ($num) = @_; $num = Math::BigInt->new($num); my $chars = [qw( 1 2 3 4 5 6 7 8 9 A B C D E F G H J K L M N P Q R S T U V W X Y Z a b c d e f g h i j k m n o p q r s t u v w x y z )]; my $base58; while ($num->is_pos) { my ($quot...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LatinSquaresInReducedForm { public static void main(String[] args) { System.out.printf("Reduced latin squares of order 4:%n"); for ( LatinSquare square : getReducedLatinSquares(4) ...
use strict; use warnings; my $n = 0; my $count; our @perms; while( ++$n <= 7 ) { $count = 0; @perms = perm( my $start = join '', 1 .. $n ); find( $start ); print "order $n size $count total @{[$count * fact($n) * fact($n-1)]}\n\n"; } sub find { @_ >= $n and return $count += ($n != 4) || print join...
Translate this program into Perl but keep the logic exactly as in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; public class Kosaraju { static class Recursive<I> { I func; } ...
use strict; use warnings; use feature 'say'; sub kosaraju { our(%k) = @_; our %g = (); our %h; my $i = 0; $g{$_} = $i++ for sort keys %k; $h{$g{$_}} = $_ for keys %g; our(%visited, @stack, @transpose, @connected); sub visit { my($u) = @_; unless ($visited{$u...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.io.*; import static java.lang.String.format; import java.util.*; public class WordSearch { static class Grid { int numAttempts; char[][] cells = new char[nRows][nCols]; List<String> solutions = new ArrayList<>(); } final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1...
use strict; use warnings; use feature <bitwise>; use Path::Tiny; use List::Util qw( shuffle ); my $size = 10; my $s1 = $size + 1; $_ = <<END; .....R.... ......O... .......S.. ........E. T........T .A........ ..C....... ...O...... ....D..... .....E.... END my @words = shuffle path('/usr/share/dict/words')->slurp =~ /^...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; public class MarkovChain { pr...
use strict; use warnings; my $file = shift || 'alice_oz.txt'; my $n = shift || 3; my $max = shift || 200; sub build_dict { my ($n, @words) = @_; my %dict; for my $i (0 .. $ my @prefix = @words[$i .. $i+$n-1]; push @{$dict{join ' ', @prefix}}, $words[$i+$n]; } return %dict; } 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; import java.util.Objects; public class ArithmeticCoding { private static class Triple<A, B, C> { A a; B b; C c; Triple(A a, B b, C c) { this.a = a; this.b = b; this.c = ...
use Math::BigInt (try => 'GMP'); sub cumulative_freq { my ($freq) = @_; my %cf; my $total = Math::BigInt->new(0); foreach my $c (sort keys %$freq) { $cf{$c} = $total; $total += $freq->{$c}; } return %cf; } sub arithmethic_coding { my ($str, $radix) = @_; my @chars = s...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ",...
use Math::Cartesian::Product; sub playfair { our($key,$from) = @_; $from //= 'J'; our $to = $from eq 'J' ? 'I' : ''; my(%ENC,%DEC,%seen,@m); sub canon { my($str) = @_; $str =~ s/[^[:alpha:]]//g; $str =~ s/$from/$to/gi; uc $str; } my @uniq = grep { ! $seen{...
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ",...
use Math::Cartesian::Product; sub playfair { our($key,$from) = @_; $from //= 'J'; our $to = $from eq 'J' ? 'I' : ''; my(%ENC,%DEC,%seen,@m); sub canon { my($str) = @_; $str =~ s/[^[:alpha:]]//g; $str =~ s/$from/$to/gi; uc $str; } my @uniq = grep { ! $seen{...
Keep all operations the same but rewrite the snippet in Perl.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList...
use strict; use warnings; my @words = <a o is pi ion par per sip miss able>; print "$_: " . word_break($_,@words) . "\n" for <a aa amiss parable opera operable inoperable permission mississippi>; sub word_break { my($word,@dictionary) = @_; my @matches; my $one_of = join '|', @dictionary; @matches = $...
Keep all operations the same but rewrite the snippet in Perl.
import java.util.Collections; import java.util.HashMap; import java.util.Map; public class ImmutableMap { public static void main(String[] args) { Map<String,Integer> hashMap = getImmutableMap(); try { hashMap.put("Test", 23); } catch (UnsupportedOperationException e)...
use strict; package LockedHash; use parent 'Tie::Hash'; use Carp; sub TIEHASH { my $cls = shift; my %h = @_; bless \%h, ref $cls || $cls; } sub STORE { my ($self, $k, $v) = @_; croak "Can't add key $k" unless exists $self->{$k}; $self->{$k} = $v; } sub FETCH { my ($self, $k) = @_; croak "No key $k" unless e...
Port the provided Java code into Perl while preserving the original functionality.
import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class DecimalToBinary { public static void main(String[] args) { for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) { String binary = decimalToBinary(new BigDecimal(s)); ...
use strict; use warnings; use feature 'say'; sub dec2bin { my($l,$r) = split /\./, shift; my $int = unpack('B*', pack('N', $l )); my $frac = unpack('B32', pack('N',4294967296 * ".$r")); "$int.$frac" =~ s/^0*(.*?)0*$/$1/r; } sub bin2dec { my($l,$r) = split /\./, shift; my $frac ...
Translate this program into Perl but keep the logic exactly as in Java.
import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class DecimalToBinary { public static void main(String[] args) { for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) { String binary = decimalToBinary(new BigDecimal(s)); ...
use strict; use warnings; use feature 'say'; sub dec2bin { my($l,$r) = split /\./, shift; my $int = unpack('B*', pack('N', $l )); my $frac = unpack('B32', pack('N',4294967296 * ".$r")); "$int.$frac" =~ s/^0*(.*?)0*$/$1/r; } sub bin2dec { my($l,$r) = split /\./, shift; my $frac ...
Produce a functionally identical Perl code for the snippet given in Java.
import java.awt.Point; import java.util.*; import static java.util.Arrays.asList; import java.util.function.Function; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toList; public class FreePolyominoesEnum { static final List<Function<Point, Point>> transforms = new ArrayLi...
use strict; use warnings; my @new = " for my $N ( 2 .. 10 ) { @new = find( @new ); my %allbest; $allbest{best($_)}++ for @new; my @show = @new = sort keys %allbest; printf "rank: %2d count: %d\n\n", $N, scalar @show; if( @show <= 12 ) { my $fmt = join '', map({ /\n/; '%' . ($+[0] + 1) . 's' }...
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.util.Arrays; import java.util.Objects; import java.util.Random; import java.util.function.Function; public class App { static class Parameters { double omega; double phip; double phig; Parameters(double omega, double phip, double phig) { this.omega = omega; ...
use strict; use warnings; use feature 'say'; use constant PI => 2 * atan2(1, 0); use constant Inf => 1e10; sub pso_init { my(%y) = @_; my $d = @{$y{'min'}}; my $n = $y{'n'}; $y{'gbval'} = Inf; $y{'gbpos'} = [(Inf) x $d]; $y{'bval'} = [(Inf) x $n]; $y{'bpos'} = [($y{'min'}) x $n]; $...
Port the provided Java code into Perl while preserving the original functionality.
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; public class IQPuzzle { public static void main(String[] args) { System.out.printf(" "); for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) { ...
@start = qw< 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 >; @moves = ( [ 0, 1, 3], [ 0, 2, 5], [ 1, 3, 6], [ 1, 4, 8], [ 2, 4, 7], [ 2, 5, 9], [ 3, 4, 5], [ 3, 6,10], [ 3, 7,12], [ 4, 7,11], [ 4, 8,13], [ 5, 8,12], [ 5, 9,14], [ 6, 7, 8], [ 7, 8, 9], [10,11,12], [11,12,13], [12,...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.io.*; import java.security.*; import java.util.*; public class SHA256MerkleTree { public static void main(String[] args) { if (args.length != 1) { System.err.println("missing file argument"); System.exit(1); } try (InputStream in = new BufferedInputStream...
use strict; use warnings; use Crypt::Digest::SHA256 'sha256' ; my @blocks; open my $fh, '<:raw', './title.png'; while ( read $fh, my $chunk, 1024 ) { push @blocks, sha256 $chunk } while ( scalar @blocks > 1 ) { my @clone = @blocks and @blocks = (); while ( @_ = splice @clone, 0, 2 ) { push @blocks, s...
Write the same algorithm in Perl as shown in this Java implementation.
import java.math.BigInteger; public class PartitionFunction { public static void main(String[] args) { long start = System.currentTimeMillis(); BigInteger result = partitions(6666); long end = System.currentTimeMillis(); System.out.println("P(6666) = " + result); System.out....
use strict; use warnings; no warnings qw(recursion); use Math::AnyNum qw(:overload); use Memoize; memoize('partitionsP'); memoize('partDiff'); sub partDiffDiff { my($n) = @_; $n%2 != 0 ? ($n+1)/2 : $n+1 } sub partDiff { my($n) = @_; $n<2 ? 1 : partDiff($n-1) + partDiffDiff($n-1) } sub partitionsP { my($n) = @_;...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.function.IntBinaryOperator; public class Nimber { public static void main(String[] args) { printTable(15, '+', (x, y) -> nimSum(x, y)); System.out.println(); printTable(15, '*', (x, y) -> nimProduct(x, y)); System.out.println(); int a = 21508, b = 42689; ...
use strict; use warnings; use feature 'say'; use Math::AnyNum qw(:overload); sub msb { my($n, $base) = (shift, 0); $base++ while $n >>= 1; $base; } sub lsb { my $n = shift; msb($n & -$n); } sub nim_sum { my($x,$y) = @_; $x ^ $y } sub nim_prod { no warnings qw(recursion); my($x,$y...
Write the same code in Perl as shown below in Java.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSynthe...
sub synthetic_division { my($numerator,$denominator) = @_; my @result = @$numerator; my $end = @$denominator-1; for my $i (0 .. @$numerator-($end+1)) { next unless $result[$i]; $result[$i] /= @$denominator[0]; $result[$i+$_] -= @$denominator[$_] * $result[$i] for 1 .. $end...
Please provide an equivalent version of this Java code in Perl.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] N = {1, -12, 0, -42}; int[] D = {1, -3}; System.out.printf("%s / %s = %s", Arrays.toString(N), Arrays.toString(D), Arrays.deepToString(extendedSynthe...
sub synthetic_division { my($numerator,$denominator) = @_; my @result = @$numerator; my $end = @$denominator-1; for my $i (0 .. @$numerator-($end+1)) { next unless $result[$i]; $result[$i] /= @$denominator[0]; $result[$i+$_] -= @$denominator[$_] * $result[$i] for 1 .. $end...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.awt.*; import javax.swing.*; public class ColorWheel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ColorWheelFrame frame = new ColorWheelFrame(); frame.setVisible(true); } ...
use Imager; use Math::Complex qw(cplx i pi); my ($width, $height) = (300, 300); my $center = cplx($width/2, $height/2); my $img = Imager->new(xsize => $width, ysize => $height); foreach my $y (0 .. $height - 1) { foreach my $x (0 .. $width - 1) { my $vec = $center - $x - $y * i; ...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; import java.util.Scanner; public class csprngBBS { public static Scanner input = new Scann...
use strict; use warnings; use GD; my $img = GD::Image->new(500, 500, 1); for my $y (0..500) { for my $x (0..500) { my $color = $img->colorAllocate(rand 256, rand 256, rand 256); $img->setPixel($x, $y, $color); } } open F, "image500.png"; print F $img->png;
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.io.*; import java.nio.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.security.*; import java.util.*; public class DuplicateFiles { public static void main(String[] args) { if (args.length != 2) { System.err.println("Directory name and minimum file size are ...
use File::Find qw(find); use File::Compare qw(compare); use Sort::Naturally; use Getopt::Std qw(getopts); my %opts; $opts{s} = 1; getopts("s:", \%opts); sub find_dups { my($dir) = @_; my @results; my %files; find { no_chdir => 1, wanted => sub { lstat; -f _ && (-s >= $opt{s} ) && push...
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.*; public class LegendrePrimeCounter { public static void main(String[] args) { LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000); for (int i = 0, n = 1; i < 10; ++i, n *= 10) System.out.printf("10^%d\t%d\n", i, counter.primeCount((n))); } pri...
use strict; use warnings; no warnings qw(recursion); use ntheory qw( nth_prime prime_count ); my (%cachephi, %cachepi); sub phi { return $cachephi{"@_"} //= do { my ($x, $aa) = @_; $aa <= 0 ? $x : phi($x, $aa - 1) - phi(int $x / nth_prime($aa), $aa - 1) }; } sub pi { return $cachepi{$_[0]} //= d...
Change the following Java code into Perl without altering its purpose.
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Coll...
my $lang = 'no language'; my $total = 0; my %blanks = (); while (<>) { if (m/<lang>/) { if (exists $blanks{lc $lang}) { $blanks{lc $lang}++ } else { $blanks{lc $lang} = 1 } $total++ } elsif (m/==\s*\{\{\s*header\s*\|\s*([^\s\}]+)\s*\}\}\s*==/) { $lang = lc $1 } } if ($total) { pr...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.util.*; public class PermutedMultiples { public static void main(String[] args) { for (int p = 100; ; p *= 10) { int max = (p * 10) / 6; for (int n = p + 2; n <= max; n += 3) { if (sameDigits(n)) { System.out.printf(" n = %d\n", n); ...
use strict; use warnings; my $n = 3; 1 while do { length($n += 3) < length 6 * $n and $n = 1 . $n =~ s/./0/gr + 2; my $sorted = join '', sort split //, $n * 6; $sorted ne join '', sort split //, $n * 1 or $sorted ne join '', sort split //, $n * 2 or $sorted ne join '', sort split //, $n * 3 or $sorted n...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.*; public class PermutedMultiples { public static void main(String[] args) { for (int p = 100; ; p *= 10) { int max = (p * 10) / 6; for (int n = p + 2; n <= max; n += 3) { if (sameDigits(n)) { System.out.printf(" n = %d\n", n); ...
use strict; use warnings; my $n = 3; 1 while do { length($n += 3) < length 6 * $n and $n = 1 . $n =~ s/./0/gr + 2; my $sorted = join '', sort split //, $n * 6; $sorted ne join '', sort split //, $n * 1 or $sorted ne join '', sort split //, $n * 2 or $sorted ne join '', sort split //, $n * 3 or $sorted n...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); ...
use strict; use warnings; use feature 'say'; use constant Inf => 1e10; sub is_p_gapful { my($d,$n) = @_; return '' unless 0 == $n % 11; my @digits = split //, $n; $d eq $digits[0] and (0 == $n % ($digits[0].$digits[-1])) and $n eq join '', reverse @digits; } for ([1, 20], [86, 15]) { my($offset,...
Write the same algorithm in Perl as shown in this Java implementation.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); ...
use strict; use warnings; use feature 'say'; use constant Inf => 1e10; sub is_p_gapful { my($d,$n) = @_; return '' unless 0 == $n % 11; my @digits = split //, $n; $d eq $digits[0] and (0 == $n % ($digits[0].$digits[-1])) and $n eq join '', reverse @digits; } for ([1, 20], [86, 15]) { my($offset,...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class ChernicksCarmichaelNumbers { public static void main(String[] args) { for ( long n = 3 ; n < 10 ; n++ ) { long m = 0; boolean foundComposite = true; List<Long> factors = null; ...
use 5.020; use warnings; use ntheory qw/:all/; use experimental qw/signatures/; sub chernick_carmichael_factors ($n, $m) { (6*$m + 1, 12*$m + 1, (map { (1 << $_) * 9*$m + 1 } 1 .. $n-2)); } sub chernick_carmichael_number ($n, $callback) { my $multiplier = ($n > 4) ? (1 << ($n-4)) : 1; for (my $m = 1 ; ;...
Write a version of this Java function in Perl with identical behavior.
import java.math.BigInteger; import java.util.*; public class WilsonPrimes { public static void main(String[] args) { final int limit = 11000; BigInteger[] f = new BigInteger[limit]; f[0] = BigInteger.ONE; BigInteger factorial = BigInteger.ONE; for (int i = 1; i < limit; ++i...
use strict; use warnings; use ntheory <primes factorial>; my @primes = @{primes( 10500 )}; for my $n (1..11) { printf "%3d: %s\n", $n, join ' ', grep { $_ >= $n && 0 == (factorial($n-1) * factorial($_-$n) - (-1)**$n) % $_**2 } @primes }
Write the same algorithm in Perl as shown in this Java implementation.
public class PrimeTriangle { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i = 2; i <= 20; ++i) { int[] a = new int[i]; for (int j = 0; j < i; ++j) a[j] = j + 1; if (findRow(a, 0, i)) pri...
use strict; use warnings; use feature 'say'; use ntheory 'is_prime'; use List::MoreUtils qw(zip slideatatime); use Algorithm::Combinatorics qw(permutations); say '1 2'; my @count = (0, 0, 1); for my $n (3..17) { my @even_nums = grep { 0 == $_ % 2 } 2..$n-1; my @odd_nums = grep { 1 == $_ % 2 } 3..$n-1; f...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import javax.xml.ws.Holder; import org.xml.sax.ErrorHandler; import...
use 5.018_002; use warnings; use Try::Tiny; use XML::LibXML; our $VERSION = 1.000_000; my $parser = XML::LibXML->new(); my $good_xml = '<a>5</a>'; my $bad_xml = '<a>5<b>foobar</b></a>'; my $xmlschema_markup = <<'END'; <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="a"...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin",...
use strict; use warnings; use feature qw(say state); use Math::AnyNum qw<:overload as_dec>; sub gen_lucas { my $b = shift; my $i = 0; return sub { state @seq = (state $v1 = 1, state $v2 = 1); ($v2, $v1) = ($v1, $v2 + $b*$v1) and push(@seq, $v1) unless defined $seq[$i+1]; return $seq...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin",...
use strict; use warnings; use feature qw(say state); use Math::AnyNum qw<:overload as_dec>; sub gen_lucas { my $b = shift; my $i = 0; return sub { state @seq = (state $v1 = 1, state $v2 = 1); ($v2, $v1) = ($v1, $v2 + $b*$v1) and push(@seq, $v1) unless defined $seq[$i+1]; return $seq...
Please provide an equivalent version of this Java code in Perl.
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class DataEncryptionStandard { private static byte[] toHexByteArray(String self) { byte[] bytes = new byte[self.length() / 2]; for (int i = 0; i < bytes.length; ++i) { bytes[i] = ((byte) Integer.parseInt(self.sub...
use strict; use warnings; use Crypt::DES; my $key = pack("H*", "0E329232EA6D0D73"); my $cipher = Crypt::DES->new($key); my $ciphertext = $cipher->encrypt(pack("H*", "8787878787878787")); print "Encoded : ", unpack("H*", $ciphertext), "\n"; print "Decoded : ", unpack("H*", $cipher->decrypt($ciphertext)), "\n...
Keep all operations the same but rewrite the snippet in Perl.
import java.util.Arrays; public class RamanujanPrimes { public static void main(String[] args) { long start = System.nanoTime(); System.out.println("First 100 Ramanujan primes:"); PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000)); for (int i = 1; i <= 100; ++i) { ...
use strict; use warnings; use ntheory 'primes'; sub count { my($n,$p) = @_; my $c = -1; do { $c++ } until $$p[$c] > $n; return $c; } my(@rp,@mem); my $primes = primes( 100_000_000 ); sub r_prime { my $n = shift; for my $x ( reverse 1 .. int 4*$n * log(4*$n) / log 2 ) { my $y = int $x ...
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.util.Arrays; public class RamanujanPrimes { public static void main(String[] args) { long start = System.nanoTime(); System.out.println("First 100 Ramanujan primes:"); PrimeCounter pc = new PrimeCounter(1 + ramanujanMax(100000)); for (int i = 1; i <= 100; ++i) { ...
use strict; use warnings; use ntheory 'primes'; sub count { my($n,$p) = @_; my $c = -1; do { $c++ } until $$p[$c] > $n; return $c; } my(@rp,@mem); my $primes = primes( 100_000_000 ); sub r_prime { my $n = shift; for my $x ( reverse 1 .. int 4*$n * log(4*$n) / log 2 ) { my $y = int $x ...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.util.*; public class ErdosSelfridge { private int[] primes; private int[] category; public static void main(String[] args) { ErdosSelfridge es = new ErdosSelfridge(1000000); System.out.println("First 200 primes:"); for (var e : es.getPrimesByCategory(200).entrySet()) {...
use strict; use warnings; use feature 'say'; use List::Util 'max'; use ntheory qw/factor/; use Primesieve qw(generate_primes); my @primes = (0, generate_primes (1, 10**8)); my %cat = (2 => 1, 3 => 1); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub ES { my ($n) = @_; my @factors = f...
Please provide an equivalent version of this Java code in Perl.
import java.util.HashMap; import java.util.Map; public class PrimeGaps { private Map<Integer, Integer> gapStarts = new HashMap<>(); private int lastPrime; private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000); public static void main(String[] args) { final int limit = 100000...
use strict; use warnings; use ntheory qw( primes ); my @gaps; my $primeref = primes( 1e9 ); for my $i ( 2 .. $ { my $diff = $primeref->[$i] - $primeref->[$i - 1]; $gaps[ $diff >> 1 ] //= $primeref->[$i - 1]; } my %first; for my $i ( 1 .. $ { defined $gaps[$i] && defined $gaps[$i-1] or next; my $diff =...
Change the following Java code into Perl without altering its purpose.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.stream.IntStream; public class WordLadde...
use strict; use warnings; my %dict; open my $handle, '<', 'unixdict.txt'; while (my $word = <$handle>) { chomp($word); my $len = length $word; if (exists $dict{$len}) { push @{ $dict{ $len } }, $word; } else { my @words = ( $word ); $dict{$len} = \@words; } } close $handle;...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { private static List<List<Integer>> fourFaceCombos() { List<List<Integer>> res = new ArrayList<>(); Set<Intege...
use strict; use warnings; sub fourFaceCombs { my %found = (); my @res = (); for (my $i = 1; $i <= 4; $i++) { for (my $j = 1; $j <= 4; $j++) { for (my $k = 1; $k <= 4; $k++) { for (my $l = 1; $l <= 4; $l++) { my @c = sort ($i, $j, $k, $l); ...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
class Doom { public static void main(String[] args) { final Date[] dates = { new Date(1800,1,6), new Date(1875,3,29), new Date(1915,12,7), new Date(1970,12,23), new Date(2043,5,14), new Date(2077,2,12), new Date(2101,4,2) ...
use strict; use warnings; sub dow ($) { my ($year, $month, $day) = split /-/; my @D = $year%($year%25?4:16) ? (3,7,7,4,2,6,4,1,5,3,7,5) : (4,1,7,2,4,6,4,1,5,3,7,5); my $c = int($year / 100); my $s = ($year % 100) / 12; my $t = ($year % 100) % 12; my $a = ( 5 * ($c % 4) + 2 ) % 7; my $b = ( $s + ...
Change the programming language of this snippet from Java to Perl without modifying what it does.
class Doom { public static void main(String[] args) { final Date[] dates = { new Date(1800,1,6), new Date(1875,3,29), new Date(1915,12,7), new Date(1970,12,23), new Date(2043,5,14), new Date(2077,2,12), new Date(2101,4,2) ...
use strict; use warnings; sub dow ($) { my ($year, $month, $day) = split /-/; my @D = $year%($year%25?4:16) ? (3,7,7,4,2,6,4,1,5,3,7,5) : (4,1,7,2,4,6,4,1,5,3,7,5); my $c = int($year / 100); my $s = ($year % 100) / 12; my $t = ($year % 100) % 12; my $a = ( 5 * ($c % 4) + 2 ) % 7; my $b = ( $s + ...
Translate this program into Perl but keep the logic exactly as in Java.
import java.util.Random; public class GaussJordan { public static void main(String[] args) { int rows = 5; Matrix m = new Matrix(rows, rows); Random r = new Random(); for (int row = 0; row < rows; ++row) { for (int column = 0; column < rows; ++column) m...
sub rref { our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) { $lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and retur...
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.Random; public class GaussJordan { public static void main(String[] args) { int rows = 5; Matrix m = new Matrix(rows, rows); Random r = new Random(); for (int row = 0; row < rows; ++row) { for (int column = 0; column < rows; ++column) m...
sub rref { our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]})); foreach my $r (0 .. $rows - 1) { $lead < $cols or return; my $i = $r; until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and retur...
Generate an equivalent Perl version of this Java code.
import java.util.function.Function; public class NumericalIntegrationAdaptiveSimpsons { public static void main(String[] args) { Function<Double,Double> f = x -> sin(x); System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e...
use strict; use warnings; sub adaptive_Simpson_quadrature { my($f, $left, $right, $eps) = @_; my $lf = eval "$f($left)"; my $rf = eval "$f($right)"; my ($mid, $midf, $whole) = Simpson_quadrature_mid($f, $left, $lf, $right, $rf); return recursive_Simpsons_asr($f, $left, $lf, $right, $rf, $eps, $whol...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.util.function.Function; public class NumericalIntegrationAdaptiveSimpsons { public static void main(String[] args) { Function<Double,Double> f = x -> sin(x); System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e...
use strict; use warnings; sub adaptive_Simpson_quadrature { my($f, $left, $right, $eps) = @_; my $lf = eval "$f($left)"; my $rf = eval "$f($right)"; my ($mid, $midf, $whole) = Simpson_quadrature_mid($f, $left, $lf, $right, $rf); return recursive_Simpsons_asr($f, $left, $lf, $right, $rf, $eps, $whol...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if ...
use strict; use warnings; use feature 'say'; use enum qw(False True); use List::Util <max uniqint product>; use Algorithm::Combinatorics qw(combinations permutations); sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } sub is_colorful { my($n) = @_;...
Write the same algorithm in Perl as shown in this Java implementation.
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if ...
use strict; use warnings; use feature 'say'; use enum qw(False True); use List::Util <max uniqint product>; use Algorithm::Combinatorics qw(combinations permutations); sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } sub is_colorful { my($n) = @_;...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import static java.lang.Math.abs; import java.util.Random; public class Fen { static Random rand = new Random(); public static void main(String[] args) { System.out.println(createFen()); } static String createFen() { char[][] grid = new char[8][8]; placeKings(grid); p...
use strict; use warnings; use feature 'say'; use utf8; use List::AllUtils <shuffle any natatime>; sub pick1 { return @_[rand @_] } sub gen_FEN { my $n = 1 + int rand 31; my @n = (shuffle(0 .. 63))[1 .. $n]; my @kings; KINGS: { for my $a (@n) { for my $b (@n) { next unless $a !=...
Generate an equivalent Perl version of this Java code.
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; ...
use strict; use warnings; use SVG; use List::Util qw(max min); use constant pi => 2 * atan2(1, 0); my $rule = 'XF-F+F-XF+F+XF-F+F-X'; my $S = 'F+F+XF+F+XF'; $S =~ s/X/$rule/g for 1..5; my (@X, @Y); my ($x, $y) = (0, 0); my $theta = pi/4; my $r = 6; for (split //, $S) { if (/F/) { push @X, sprintf...
Write a version of this Java function in Perl with identical behavior.
public class RhondaNumbers { public static void main(String[] args) { final int limit = 15; for (int base = 2; base <= 36; ++base) { if (isPrime(base)) continue; System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base); int numbers[]...
use strict; use warnings; use feature 'say'; use ntheory qw<is_prime factor vecsum vecprod todigitstring todigits>; sub rhonda { my($b, $cnt) = @_; my(@r,$n); while (++$n) { push @r, $n if ($b * vecsum factor($n)) == vecprod todigits($n,$b); return @r if $cnt == @r; } } for my $b (grep...