Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5}; for (int i = 0; i < s.length; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) System.out.println(i); ...
@s = <1 2 2 3 4 4 5>; for ($i = 0; $i < 7; $i++) { $curr = $s[$i]; if ($i > 1 and $curr == $prev) { print "$i\n" } $prev = $curr; }
Convert this Java block to Perl, preserving its control flow and logic.
import java.util.Arrays; public class OEIS_A005179 { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } ...
use strict; use warnings; use ntheory 'divisors'; print "First 15 terms of OEIS: A005179\n"; for my $n (1..15) { my $l = 0; while (++$l) { print "$l " and last if $n == divisors($l); } }
Keep all operations the same but rewrite the snippet in Perl.
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; ...
binmode(STDOUT, ":utf8"); our @sparks=map {chr} 0x2581 .. 0x2588; sub sparkline :prototype(@) { my @n=map {0+$_} grep {length} @_ or return ""; my($min,$max)=($n[0])x2; if (@n>1) { for (@n[1..$ if ($_<$min) { $min=$_ } elsif ($_>$max) { $max=$_ } } } my $sp...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
public class LevenshteinAlignment { public static String[] alignment(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); int[][] costs = new int[a.length()+1][b.length()+1]; for (int j = 0; j <= b.length(); j++) costs[0][j] = j; for (int i = ...
use strict; use warnings; use List::Util qw(min); sub levenshtein_distance_alignment { my @s = ('^', split //, shift); my @t = ('^', split //, shift); my @A; @{$A[$_][0]}{qw(d s t)} = ($_, join('', @s[1 .. $_]), ('~' x $_)) for 0 .. $ @{$A[0][$_]}{qw(d s t)} = ($_, ('-' x $_), join '', @t[1 .. ...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>(); for (E x : n) { Node<E> node = new Node<E>(); node.value = x; int i = Collections.binarySearch(pileTops, ...
use strict; sub lis { my @l = map [], 1 .. @_; push @{$l[0]}, +$_[0]; for my $i (1 .. @_-1) { for my $j (0 .. $i - 1) { if ($_[$j] < $_[$i] and @{$l[$i]} < @{$l[$j]} + 1) { $l[$i] = [ @{$l[$j]} ]; } } push @{$l[$i]}, $_[$i]; } my ($max...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { ...
use strict; use warnings; @ARGV = 'unixdict.txt'; my $skew = join '', map { s/^.{9}\K.+//r } my @words = grep length() > 9, <>; my %dict = map { $_ => 1 } grep length == 10, @words; my %seen; my $nextch = '.{10}(\\w)' x 8; while( $skew =~ /^(\w)(?=$nextch)/gms ) { my $new = join '', @{^CAPTURE}, "\n"; $dict{$...
Convert this Java snippet to Perl and keep its semantics consistent.
public static void main(String... args){ HashMap<String, Integer> vars = new HashMap<String, Integer>(); vars.put("Variable name", 3); vars.put("Next variable name", 5); Scanner sc = new Scanner(System.in); String str = sc.next(); vars.put(str,...
print "Enter a variable name: "; $varname = <STDIN>; chomp($varname); $$varname = 42; print "$foo\n";
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Ma...
use strict; use warnings; use feature 'say'; sub integral { my($n) = @_; (length($n) % 2 != 0 ? '0' . $n : $n) =~ /../g } sub fractional { my($n) = @_; (length($n) % 2 == 0 ? $n . '0' : $n) =~ /../g } sub SpigotSqrt { my($in) = @_; my(@dividends, @fractional, $dividend, $quotient, $remainder, $accum); ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Ma...
use strict; use warnings; use feature 'say'; sub integral { my($n) = @_; (length($n) % 2 != 0 ? '0' . $n : $n) =~ /../g } sub fractional { my($n) = @_; (length($n) % 2 == 0 ? $n . '0' : $n) =~ /../g } sub SpigotSqrt { my($in) = @_; my(@dividends, @fractional, $dividend, $quotient, $remainder, $accum); ...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) {...
use strict; use warnings; use feature 'say'; use List::AllUtils <max head firstidx uniqint>; use ntheory <primes is_semiprime forsetproduct>; sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.*; public class BrilliantNumbers { public static void main(String[] args) { var primesByDigits = getPrimesByDigits(100000000); System.out.println("First 100 brilliant numbers:"); List<Integer> brilliantNumbers = new ArrayList<>(); for (var primes : primesByDigits) {...
use strict; use warnings; use feature 'say'; use List::AllUtils <max head firstidx uniqint>; use ntheory <primes is_semiprime forsetproduct>; sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.util.Arrays; import java.util.BitSet; import org.apache.commons.lang3.ArrayUtils; public class OrderDisjointItems { public static void main(String[] args) { final String[][] MNs = {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C...
sub dsort { my ($m, $n) = @_; my %h; $h{$_}++ for @$n; map $h{$_}-- > 0 ? shift @$n : $_, @$m; } for (split "\n", <<"IN") the cat sat on the mat | mat cat the cat sat on the mat | cat mat A B C A B C A B C | C A C A A B C A B D A B E | E A D...
Change the following Java code into Perl without altering its purpose.
import java.util.Arrays; import java.util.Comparator; public class RJSortStability { public static void main(String[] args) { String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", }; String[] cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String ...
use sort 'stable';
Translate this program into Perl but keep the logic exactly as in Java.
public static void main(String[] args) { System.out.println(concat("Rosetta", "Code", ":")); } public static String concat(String a, String b, String c) { return a + c + c + b; } Rosetta::Code
$ perl -de1 Loading DB routines from perl5db.pl version 1.3 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(-e:1): 1 DB<1> sub f {my ($s1, $s2, $sep) = @_; $s1 . $sep . $sep . $s2} DB<2> p f('Rosetta', 'Code', ':') Rosetta::Code DB<3> q
Convert this Java block to Perl, preserving its control flow and logic.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class...
sub eval_with_x {my $code = shift; my $x = shift; my $first = eval $code; $x = shift; return eval($code) - $first;} print eval_with_x('3 * $x', 5, 10), "\n";
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class...
sub eval_with_x {my $code = shift; my $x = shift; my $first = eval $code; $x = shift; return eval($code) - $first;} print eval_with_x('3 * $x', 5, 10), "\n";
Produce a functionally identical Perl code for the snippet given in Java.
public class ReallyLameTranslationOfJ { public static void main(String[] args) { String s = "She was a soul stripper. She took my heart!"; System.out.println(cheapTrick(s)); System.out.println(cheapTrick(cheapTrick(s))); } static String cheapTrick(String s) { if (s.contains...
my %swaps = ( 'she' => 'he', 'his' => 'her', ); $swaps{ $swaps{$_} } = $_ for keys %swaps; $swaps{ ucfirst $swaps{$_} } = ucfirst $_ for keys %swaps; sub gender_swap { my($s) = @_; $s =~ s/\b$_\b/_$swaps{$_}/g for keys %swaps; $s =~ s/_//g; ...
Keep all operations the same but rewrite the snippet in Perl.
public class ReallyLameTranslationOfJ { public static void main(String[] args) { String s = "She was a soul stripper. She took my heart!"; System.out.println(cheapTrick(s)); System.out.println(cheapTrick(cheapTrick(s))); } static String cheapTrick(String s) { if (s.contains...
my %swaps = ( 'she' => 'he', 'his' => 'her', ); $swaps{ $swaps{$_} } = $_ for keys %swaps; $swaps{ ucfirst $swaps{$_} } = ucfirst $_ for keys %swaps; sub gender_swap { my($s) = @_; $s =~ s/\b$_\b/_$swaps{$_}/g for keys %swaps; $s =~ s/_//g; ...
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.Fo...
my ($a, $b) = (-5, 7); $ans = eval 'abs($a * $b)';
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.Fo...
my ($a, $b) = (-5, 7); $ans = eval 'abs($a * $b)';
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.math.BigInteger; import static java.util.Arrays.stream; import java.util.*; import static java.util.stream.Collectors.*; public class Test3 { static BigInteger rank(int[] x) { String s = stream(x).mapToObj(String::valueOf).collect(joining("F")); return new BigInteger(s, 16); } ...
use bigint; use ntheory qw(fromdigits todigitstring); use feature 'say'; sub rank { join '', fromdigits(join('a',@_), 11) } sub unrank { split 'a', todigitstring(@_[0], 11) } say join ' ', @n = qw<12 11 0 7 9 15 15 5 7 13 5 5>; say $n = rank(@n); say join ' ', unrank $n;
Translate the given Java code snippet into Perl without altering its behavior.
import java.util.*; public class RandomShuffle { public static void main(String[] args) { Random rand = new Random(); List<Integer> list = new ArrayList<>(); for (int j = 1; j <= 20; ++j) list.add(j); Collections.shuffle(list, rand); System.out.println(list); ...
use strict; use warnings; use List::Util qw( shuffle ); print "@{[ shuffle 1 .. 20 ]}\n" for 1 .. 5;
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) throws IOException { final int endOfFile = -1; try ( FileReader reader = new FileReader("input.txt", StandardCharsets.UTF_8) ) { while (...
binmode STDOUT, ':utf8'; open my $fh, "<:encoding(UTF-8)", "input.txt" or die "$!\n"; while (read $fh, my $char, 1) { printf "got character $char [U+%04x]\n", ord $char; } close $fh;
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; impo...
use strict; use warnings; use Tk; my $mw; my $win; my $lab; sub openWin { if( $win ) { $win->deiconify; $win->wm('state', 'normal'); } else { eval { $win->destroy } if $win; $win = $mw->Toplevel; $win->Label(-text => "This is the window being manipulated") ->pack(-fill => 'both', -expand => 1); $la...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; ...
use strict; use warnings; use List::Util 'any'; use Time::HiRes qw(sleep); use List::AllUtils <pairwise pairs>; use utf8; binmode STDOUT, ':utf8'; my $coins = shift || 100; my $peg_lines = shift || 13; my $row_count = $peg_lines; my $peg = '^'; my @coin_icons = ("\N{UPPER HALF BLOCK}", "\N{LOWER HALF B...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.io.*; import java.util.*; public class PrimeDescendants { public static void main(String[] args) { try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) { printPrimeDesc(writer, 100); } catch (IOException ex) { ex.printStackTrace(); ...
use List::Util qw(sum uniq); use ntheory qw(nth_prime); my $max = 99; my %tree; sub allocate { my($n, $i, $sum,, $prod) = @_; $i //= 0; $sum //= 0; $prod //= 1; for my $k (0..$max) { next if $k < $i; my $p = nth_prime($k+1); if (($sum + $p) <= $max) { allocate($n, $k, ...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toS...
sub circlesort { our @x; local *x = shift; my($beg,$end) = @_; my $swaps = 0; if ($beg < $end) { my $lo = $beg; my $hi = $end; while ($lo < $hi) { if ($x[$lo] > $x[$hi]) { @x[$lo,$hi] = @x[$hi,$lo]; ++$swaps; } ...
Please provide an equivalent version of this Java code in Perl.
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cas...
sub brace_expand { my $input = shift; my @stack = ([my $current = ['']]); while ($input =~ /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx) { if ($1 eq '{') { push @stack, [$current = ['']]; } elsif ($1 eq ',' && @stack > 1) { push @{$stack[-1]}, ($current = ...
Write the same algorithm in Perl as shown in this Java implementation.
package intersectingNumberWheels; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; public class WheelController { private static final String IS_NUMBER = "[0-9]"; private static final int TWENTY = 20; private static Map<String, Whe...
use strict; use warnings; use feature 'say'; sub get_next { my($w,%wheels) = @_; my $wh = \@{$wheels{$w}}; my $value = $$wh[0][$$wh[1]]; $$wh[1] = ($$wh[1]+1) % @{$$wh[0]}; defined $wheels{$value} ? get_next($value,%wheels) : $value; } sub spin_wheels { my(%wheels) = @_; say "$_: " . join...
Write a version of this Java function in Perl with identical behavior.
package intersectingNumberWheels; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; public class WheelController { private static final String IS_NUMBER = "[0-9]"; private static final int TWENTY = 20; private static Map<String, Whe...
use strict; use warnings; use feature 'say'; sub get_next { my($w,%wheels) = @_; my $wh = \@{$wheels{$w}}; my $value = $$wh[0][$$wh[1]]; $$wh[1] = ($$wh[1]+1) % @{$$wh[0]}; defined $wheels{$value} ? get_next($value,%wheels) : $value; } sub spin_wheels { my(%wheels) = @_; say "$_: " . join...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
public static Color getColorAt(int x, int y){ return new Robot().getPixelColor(x, y); }
use strict; use warnings; use GD; my $file = '/tmp/one-pixel-screen-capture.png'; system "screencapture -R 123,456,1,1 $file"; my $image = GD::Image->newFromPng($file); my $index = $image->getPixel(0,0); my($red,$green,$blue) = $image->rgb($index); print "RGB: $red, $green, $blue\n"; unlink $file;
Produce a functionally identical Perl code for the snippet given in Java.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.regex.M...
package YahooSearch; use Encode; use HTTP::Cookies; use WWW::Mechanize; sub apply (&$) {my $f = shift; local $_ = shift; $f->(); return $_;} my $search_prefs = 'v=1&n=100&sm=' . apply {s/([^a-zA-Z0-9])/sprintf '%%%02X', ord $1/ge} join '|', map {'!' . $_} qw(hsb Zq0 XbM sss dDO VFM RQh uZ0 Fxe...
Produce a language-to-language conversion: from Java to Perl, same semantics.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
use strict; sub circles { my ($x1, $y1, $x2, $y2, $r) = @_; return "Radius is zero" if $r == 0; return "Coincident points gives infinite number of circles" if $x1 == $x2 and $y1 == $y2; my ($dx, $dy) = ($x2 - $x1, $y2 - $y1); my $q = sqrt($dx**2 + $dy**2); return "Separation of points gr...
Write the same algorithm in Perl as shown in this Java implementation.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
use strict; sub circles { my ($x1, $y1, $x2, $y2, $r) = @_; return "Radius is zero" if $r == 0; return "Coincident points gives infinite number of circles" if $x1 == $x2 and $y1 == $y2; my ($dx, $dy) = ($x2 - $x1, $y2 - $y1); my $q = sqrt($dx**2 + $dy**2); return "Separation of points gr...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.Arrays; import java.util.HashSet; public class VampireNumbers{ private static int numDigits(long num){ return Long.toString(Math.abs(num)).length(); } private static boolean fangCheck(long orig, long fang1, long fang2){ if(Long.toString(fang1).endsWith("0") && Long.toStrin...
use warnings; use strict; use feature qw(say); sub fangs { my $vampire = shift; my $length = length 0 + $vampire; return if $length % 2; my $fang_length = $length / 2; my $from = '1' . '0' x ($fang_length - 1); my $to = '9' x $fang_length; my $sorted = join q(), sort ...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arr...
use strict; use warnings; my @pts = ('', qw( 01 23 03 12 012 13 013 132 0132) ); my @dots = qw( 4-0 8-0 4-4 8-4 ); my @images = map { sprintf("%-9s\n", "$_:") . draw($_) } 0, 1, 20, 300, 4000, 5555, 6789, 1133; for ( 1 .. 13 ) { s/(.+)\n/ print " $1"; '' /e for @images; print "\n"; } sub draw { my $...
Write the same algorithm in Perl as shown in this Java implementation.
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arr...
use strict; use warnings; my @pts = ('', qw( 01 23 03 12 012 13 013 132 0132) ); my @dots = qw( 4-0 8-0 4-4 8-4 ); my @images = map { sprintf("%-9s\n", "$_:") . draw($_) } 0, 1, 20, 300, 4000, 5555, 6789, 1133; for ( 1 .. 13 ) { s/(.+)\n/ print " $1"; '' /e for @images; print "\n"; } sub draw { my $...
Please provide an equivalent version of this Java code in Perl.
import java.util.Arrays; import java.util.Collections; import java.util.HashSet; public class PokerHandAnalyzer { final static String faces = "AKQJT98765432"; final static String suits = "HDSC"; final static String[] deck = buildDeck(); public static void main(String[] args) { System.out.prin...
use strict; use warnings; use utf8; use feature 'say'; use open qw<:encoding(utf-8) :std>; package Hand { sub describe { my $str = pop; my $hand = init($str); return "$str: INVALID" if !$hand; return analyze($hand); } sub init { (my $str = lc shift) =~ tr/23456789...
Generate an equivalent Perl version of this Java code.
import java.util.Arrays; import java.util.Collections; import java.util.HashSet; public class PokerHandAnalyzer { final static String faces = "AKQJT98765432"; final static String suits = "HDSC"; final static String[] deck = buildDeck(); public static void main(String[] args) { System.out.prin...
use strict; use warnings; use utf8; use feature 'say'; use open qw<:encoding(utf-8) :std>; package Hand { sub describe { my $str = pop; my $hand = init($str); return "$str: INVALID" if !$hand; return analyze($hand); } sub init { (my $str = lc shift) =~ tr/23456789...
Generate an equivalent Perl version of this Java code.
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n)...
use strict; use warnings; use GD; my @fword = ( undef, 1, 0 ); sub fword { my $n = shift; return $fword[$n] if $n<3; return $fword[$n] //= fword($n-1).fword($n-2); } my $size = 3000; my $im = GD::Image->new($size,$size); my $white = $im->colorAllocate(255,255,255); my $black = $im->colorAllocate(0,0,0); $i...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.util.*; public class PenneysGame { public static void main(String[] args) { Random rand = new Random(); String compChoice = "", playerChoice; if (rand.nextBoolean()) { for (int i = 0; i < 3; i++) compChoice += "HT".charAt(rand.nextInt(2)); ...
use 5.020; use strict; use warnings; binaryRand() == 0 ? flipCoin(userFirst()) : flipCoin(compFirst()); sub binaryRand { return int(rand(2)); } sub convert { my $randNum = binaryRand(); if($randNum == 0) { return "T" } else { return "H"; } } sub uSeq { print("...
Port the provided Java code into Perl while preserving the original functionality.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting le...
my $levels = 6; my $side = 512; my $height = get_height($side); sub get_height { my($side) = @_; $side * sqrt(3) / 2 } sub triangle { my($x1, $y1, $x2, $y2, $x3, $y3, $fill, $animate) = @_; my $svg; $svg .= qq{<polygon points="$x1,$y1 $x2,$y2 $x3,$y3"}; $svg .= qq{ style="fill: $fill; stroke-width: ...
Change the following Java code into Perl without altering its purpose.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting le...
my $levels = 6; my $side = 512; my $height = get_height($side); sub get_height { my($side) = @_; $side * sqrt(3) / 2 } sub triangle { my($x1, $y1, $x2, $y2, $x3, $y3, $fill, $animate) = @_; my $svg; $svg .= qq{<polygon points="$x1,$y1 $x2,$y2 $x3,$y3"}; $svg .= qq{ style="fill: $fill; stroke-width: ...
Port the following code from Java to Perl with equivalent syntax and logic.
import java.util.*; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; public class Nonoblock { public static void main(String[] args) { printBlock("21", 5); printBlock("", 5); printBlock("8", 10); printBlock("2323", 15); printBlock("23...
use strict; use warnings; while( <DATA> ) { print "\n$_", tr/\n/=/cr; my ($cells, @blocks) = split; my $letter = 'A'; $_ = join '.', map { $letter++ x $_ } @blocks; $cells < length and print("no solution\n"), next; $_ .= '.' x ($cells - length) . "\n"; 1 while print, s/^(\.*)\b(.*?)\b(\w+)\.\B/$2$1.$3/...
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.*; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; public class Nonoblock { public static void main(String[] args) { printBlock("21", 5); printBlock("", 5); printBlock("8", 10); printBlock("2323", 15); printBlock("23...
use strict; use warnings; while( <DATA> ) { print "\n$_", tr/\n/=/cr; my ($cells, @blocks) = split; my $letter = 'A'; $_ = join '.', map { $letter++ x $_ } @blocks; $cells < length and print("no solution\n"), next; $_ .= '.' x ($cells - length) . "\n"; 1 while print, s/^(\.*)\b(.*?)\b(\w+)\.\B/$2$1.$3/...
Convert this Java block to Perl, preserving its control flow and logic.
import java.util.List; public class Main { private static class Range { int start; int end; boolean print; public Range(int s, int e, boolean p) { start = s; end = e; print = p; } } public static void main(String[] args) { ...
use strict; use warnings; use feature 'say'; use Lingua::EN::Numbers qw(num2en); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub e_ban { my($power) = @_; my @n; for (1..10**$power) { next unless 0 == $_%2; next if $_ =~ /[789]/ or /[12].$/ or /[135]..$/ or /[135]....
Convert this Java block to Perl, preserving its control flow and logic.
import java.util.List; public class Main { private static class Range { int start; int end; boolean print; public Range(int s, int e, boolean p) { start = s; end = e; print = p; } } public static void main(String[] args) { ...
use strict; use warnings; use feature 'say'; use Lingua::EN::Numbers qw(num2en); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub e_ban { my($power) = @_; my @n; for (1..10**$power) { next unless 0 == $_%2; next if $_ =~ /[789]/ or /[12].$/ or /[135]..$/ or /[135]....
Translate this program into Perl but keep the logic exactly as in Java.
import java.math.BigInteger; public class MayanNumerals { public static void main(String[] args) { for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) { displayMyan(BigInteger.valueOf(base10)); System.out.printf("%n");...
use ntheory qw/fromdigits todigitstring/; my $t_style = '"border-collapse: separate; text-align: center; border-spacing: 3px 0px;"'; my $c_style = '"border: solid black 2px;background-color: 'border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;'. 'vertical-align: bottom;width: 3.25em;"'; sub ca...
Keep all operations the same but rewrite the snippet in Perl.
public class Test { static boolean valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) if (nuts % n != 1) return false; return nuts != 0 && (nuts % n == 0); } public static void main(String[] args) { int x = 0; for (int n ...
use bigint; for $sailors (1..15) { check( $sailors, coconuts( 0+$sailors ) ) } sub is_valid { my($sailors, $nuts) = @_; return 0, 0 if $sailors == 1 and $nuts == 1; my @shares; for (1..$sailors) { return () unless ($nuts % $sailors) == 1; push @shares, int ($nuts-1)/$sailors; $...
Transform the following Java implementation into Perl, maintaining the same output and logic.
public class Test { static boolean valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) if (nuts % n != 1) return false; return nuts != 0 && (nuts % n == 0); } public static void main(String[] args) { int x = 0; for (int n ...
use bigint; for $sailors (1..15) { check( $sailors, coconuts( 0+$sailors ) ) } sub is_valid { my($sailors, $nuts) = @_; return 0, 0 if $sailors == 1 and $nuts == 1; my @shares; for (1..$sailors) { return () unless ($nuts % $sailors) == 1; push @shares, int ($nuts-1)/$sailors; $...
Write the same code in Perl as shown below in Java.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class NauticalBell extends Thread { public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.join...
use utf8; binmode STDOUT, ":utf8"; use DateTime; $| = 1; my @watch = <Middle Morning Forenoon Afternoon Dog First>; my @ordinal = <One Two Three Four Five Six Seven Eight>; my $thishour; my $thisminute = ''; while () { my $utc = DateTime->now( time_zone => 'UTC' ); if ($utc->minute =~ /^(00|30)$/ and $utc-...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class NauticalBell extends Thread { public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.join...
use utf8; binmode STDOUT, ":utf8"; use DateTime; $| = 1; my @watch = <Middle Morning Forenoon Afternoon Dog First>; my @ordinal = <One Two Three Four Five Six Seven Eight>; my $thishour; my $thisminute = ''; while () { my $utc = DateTime->now( time_zone => 'UTC' ); if ($utc->minute =~ /^(00|30)$/ and $utc-...
Translate this program into Perl but keep the logic exactly as in Java.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
use MIDI::Simple; set_tempo 500_000; n 60; n 62; n 64; n 65; n 67; n 69; n 71; n 72; write_score 'scale.mid';
Convert the following code from Java to Perl, ensuring the logic remains intact.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
use MIDI::Simple; set_tempo 500_000; n 60; n 62; n 64; n 65; n 67; n 69; n 71; n 72; write_score 'scale.mid';
Translate the given Java code snippet into Perl without altering its behavior.
import java.awt.*; import java.awt.event.ActionEvent; import javax.swing.*; public class PolySpiral extends JPanel { double inc = 0; public PolySpiral() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(40, (ActionEvent e) -> { inc = (inc +...
use strict; use warnings; use Tk; use List::Util qw( min ); my $size = 500; my ($width, $height, $x, $y, $dist); my $angleinc = 0; my $active = 0; my $wait = 1000 / 30; my $radian = 90 / atan2 1, 0; my $mw = MainWindow->new; $mw->title( 'Polyspiral' ); my $c = $mw->Canvas( -width => $size, -height => $size, -rel...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.awt.*; import java.awt.event.ActionEvent; import javax.swing.*; public class PolySpiral extends JPanel { double inc = 0; public PolySpiral() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(40, (ActionEvent e) -> { inc = (inc +...
use strict; use warnings; use Tk; use List::Util qw( min ); my $size = 500; my ($width, $height, $x, $y, $dist); my $angleinc = 0; my $active = 0; my $wait = 1000 / 30; my $radian = 90 / atan2 1, 0; my $mw = MainWindow->new; $mw->title( 'Polyspiral' ); my $c = $mw->Canvas( -width => $size, -height => $size, -rel...
Translate the given Java code snippet into Perl without altering its behavior.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { st...
use strict; use warnings; use Imager; my %type = ( Taxicab => sub { my($px, $py, $x, $y) = @_; abs($px - $x) + abs($py - $y) }, Euclidean => sub { my($px, $py, $x, $y) = @_; ($px - $x)**2 + ($py - $y)**2 }, Minkowski => sub { my($px, $py, $x, $y) = @_; abs($px - $x)**3 + abs($py - $y)**3 }...
Please provide an equivalent version of this Java code in Perl.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { st...
use strict; use warnings; use Imager; my %type = ( Taxicab => sub { my($px, $py, $x, $y) = @_; abs($px - $x) + abs($py - $y) }, Euclidean => sub { my($px, $py, $x, $y) = @_; ($px - $x)**2 + ($py - $y)**2 }, Minkowski => sub { my($px, $py, $x, $y) = @_; abs($px - $x)**3 + abs($py - $y)**3 }...
Produce a functionally identical Perl code for the snippet given in Java.
import java.io.IOException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapConnectionDemo { public static void main(String[] args) throws LdapExcepti...
use Net::LDAP; my $ldap = Net::LDAP->new('ldap://ldap.example.com') or die $@; my $mesg = $ldap->bind( $bind_dn, password => $bind_pass );
Ensure the translated Perl code behaves exactly like the original Java snippet.
package hu.pj.alg.test; import hu.pj.alg.BoundedKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class BoundedKnapsackForTourists { public BoundedKnapsackForTourists() { BoundedKnapsack bok = new BoundedKnapsack(400); bok.add("map", 9, 150, 1); bok...
use strict; my $raw = <<'TABLE'; map 9 150 1 compass 13 35 1 water 153 200 2 sandwich 50 60 2 glucose 15 60 2 tin 68 45 3 banana 27 60 3 apple 39 40 3 cheese 23 30 1 beer 52 10 1 suntanc...
Write the same code in Perl as shown below in Java.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Hidato { private static int[][] board; private static int[] given, start; public static void main(String[] args) { String[] input = {"_ 33 35 _ _ . . .", "_ _ 24 22 _ . . .", "_ _...
use strict; use List::Util 'max'; our (@grid, @known, $n); sub show_board { for my $r (@grid) { print map(!defined($_) ? ' ' : $_ ? sprintf("%3d", $_) : ' __' , @$r), "\n" } } sub parse_board { @grid = map{[map(/^_/ ? 0 : /^\./ ? undef: $_, split ' ')]} split "\n", shift(); for my $y (0 .. $ ...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Hidato { private static int[][] board; private static int[] given, start; public static void main(String[] args) { String[] input = {"_ 33 35 _ _ . . .", "_ _ 24 22 _ . . .", "_ _...
use strict; use List::Util 'max'; our (@grid, @known, $n); sub show_board { for my $r (@grid) { print map(!defined($_) ? ' ' : $_ ? sprintf("%3d", $_) : ' __' , @$r), "\n" } } sub parse_board { @grid = map{[map(/^_/ ? 0 : /^\./ ? undef: $_, split ' ')]} split "\n", shift(); for my $y (0 .. $ ...
Keep all operations the same but rewrite the snippet in Perl.
import java.util.Arrays; import java.util.LinkedList; public class Strand{ public static <E extends Comparable<? super E>> LinkedList<E> strandSort(LinkedList<E> list){ if(list.size() <= 1) return list; LinkedList<E> result = new LinkedList<E>(); while(list.size() > 0){ LinkedList<E> sorted = new Linked...
use strict; use warnings; use feature 'say'; sub merge { my ($x, $y) = @_; my @out; while (@$x and @$y) { my $t = $x->[-1] <=> $y->[-1]; if ($t == 1) { unshift @out, pop @$x } elsif ($t == -1) { unshift @out, pop @$y } else { splice @out, 0, 0, pop(@$x), pop(...
Please provide an equivalent version of this Java code in Perl.
import java.text.DecimalFormat; public class AnglesNormalizationAndConversion { public static void main(String[] args) { DecimalFormat formatAngle = new DecimalFormat("######0.000000"); DecimalFormat formatConv = new DecimalFormat("###0.0000"); System.out.printf(" ...
use strict; use warnings; use feature 'say'; use POSIX 'fmod'; my $tau = 2 * 4*atan2(1, 1); my @units = ( { code => 'd', name => 'degrees' , number => 360 }, { code => 'g', name => 'gradians', number => 400 }, { code => 'm', name => 'mills' , number => 6400 }, { code => 'r', name => 'radians' , num...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class XMLPars...
use XML::XPath qw(); my $x = XML::XPath->new('<inventory ... </inventory>'); [$x->findnodes('//item[1]')->get_nodelist]->[0]; print $x->findnodes_as_string('//price'); $x->findnodes('//name')->get_nodelist;
Change the following Java code into Perl without altering its purpose.
import java.util.*; public class RankingMethods { final static String[] input = {"44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"}; public static void main(String[] args) { int len = input.length; Map<String, int[]> map = new TreeMap<>((a, b) -...
my %scores = ( 'Solomon' => 44, 'Jason' => 42, 'Errol' => 42, 'Garry' => 41, 'Bernard' => 41, 'Barry' => 41, 'Stephen' => 39 ); sub tiers { my(%s) = @_; my(%h); push @{$h{$s{$_}}}, $_ for keys %s; @{\%h}{reverse sort keys %h}; } sub standard { my(%s) = @_; my($resul...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); ...
use warnings; use strict; my $needspeeling = 0; my $seedsremoved = 1; my $numberofstrawberries = 62000; my $numberofbananas = 1024; my $favouritefruit = 'bananas'; my @out; sub config { my (@config) = <DATA>; push @config, "NUMBEROFSTRAWBERRIES $numberofstrawberries\n" unle...
Write the same code in Perl as shown below in Java.
import java.util.HashMap; import java.util.Map; import java.util.regex.*; public class StraddlingCheckerboard { final static String[] keyvals = {"H:0", "O:1", "L:2", "M:4", "E:5", "S:6", "R:8", "T:9", "A:30", "B:31", "C:32", "D:33", "F:34", "G:35", "I:36", "J:37", "K:38", "N:39", "P:70", "Q:71", "...
use strict; use warnings; use feature 'say'; use List::Util <min max>; my(%encode,%decode,@table); sub build { my($u,$v,$alphabet) = @_; my(@flat_board,%p2c,%c2p); my $numeric_escape = '/'; @flat_board = split '', uc $alphabet; splice @flat_board, min($u,$v), 0, undef; splice @flat_board, max...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.io.BufferedReader; import java.io.FileReader; public class IbeforeE { public static void main(String[] args) { IbeforeE now=new IbeforeE(); String wordlist="unixdict.txt"; if(now.isPlausibleRule(wordlist)) System.out.println("Rule is plausible."); else System.out.println("Rule is not plaus...
use warnings; use strict; sub result { my ($support, $against) = @_; my $ratio = sprintf '%.2f', $support / $against; my $result = $ratio >= 2; print "$support / $against = $ratio. ", 'NOT ' x !$result, "PLAUSIBLE\n"; return $result; } my @keys = qw(ei cei ie cie); my %count; while (<>) { ...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.io.BufferedReader; import java.io.FileReader; public class IbeforeE { public static void main(String[] args) { IbeforeE now=new IbeforeE(); String wordlist="unixdict.txt"; if(now.isPlausibleRule(wordlist)) System.out.println("Rule is plausible."); else System.out.println("Rule is not plaus...
use warnings; use strict; sub result { my ($support, $against) = @_; my $ratio = sprintf '%.2f', $support / $against; my $result = $ratio >= 2; print "$support / $against = $ratio. ", 'NOT ' x !$result, "PLAUSIBLE\n"; return $result; } my @keys = qw(ei cei ie cie); my %count; while (<>) { ...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AbelianSandpile { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Frame frame = new Frame(); frame.setVisible(true); ...
use strict; use warnings; use feature 'bitwise'; my ($high, $wide) = split ' ', qx(stty size); my $mask = "\0" x $wide . ("\0" . "\177" x ($wide - 2) . "\0") x ($high - 5) . "\0" x $wide; my $pile = $mask =~ s/\177/ rand() < 0.02 ? chr 64 + rand 20 : "\0" /ger; for (1 .. 1e6) { print "\e[H", $pile =~ tr/\0-\177...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AbelianSandpile { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Frame frame = new Frame(); frame.setVisible(true); ...
use strict; use warnings; use feature 'bitwise'; my ($high, $wide) = split ' ', qx(stty size); my $mask = "\0" x $wide . ("\0" . "\177" x ($wide - 2) . "\0") x ($high - 5) . "\0" x $wide; my $pile = $mask =~ s/\177/ rand() < 0.02 ? chr 64 + rand 20 : "\0" /ger; for (1 .. 1e6) { print "\e[H", $pile =~ tr/\0-\177...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c)...
use strict; use warnings; sub plot { my ($x, $y, $c) = @_; printf "plot %d %d %.1f\n", $x, $y, $c if $c; } sub ipart { int shift; } sub round { int( 0.5 + shift ); } sub fpart { my $x = shift; $x - int $x; } sub rfpart { 1 - fpart(shift); } sub drawLine { my ($x0, $y0, $x1, $y1) = @_; my $plot = \&plo...
Port the provided Java code into Perl while preserving the original functionality.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class NextHighestIntFromDigits { public static void main(String[] args) { for ( String s : new String[] {"0", ...
use strict; use warnings; use feature 'say'; use bigint; use List::Util 'first'; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub next_greatest_index { my($str) = @_; my @i = reverse split //, $str; @i-1 - (1 + first { $i[$_] > $i[$_+1] } 0 .. @i-1); } sub next_greatest_integer {...
Write the same algorithm in Perl as shown in this Java implementation.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class NextHighestIntFromDigits { public static void main(String[] args) { for ( String s : new String[] {"0", ...
use strict; use warnings; use feature 'say'; use bigint; use List::Util 'first'; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub next_greatest_index { my($str) = @_; my @i = reverse split //, $str; @i-1 - (1 + first { $i[$_] > $i[$_+1] } 0 .. @i-1); } sub next_greatest_integer {...
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.awt.Robot public static void type(String str){ Robot robot = new Robot(); for(char ch:str.toCharArray()){ if(Character.isUpperCase(ch)){ robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress((int)ch); robot.keyRelease((int)ch); robot.keyRelease(KeyEvent.VK_SHIFT);...
$target = "/dev/pts/51"; $TIOCSTI = 0x5412 ; open(TTY,">$target") or die "cannot open $target" ; $b="sleep 99334 &\015"; @c=split("",$b); sleep(2); foreach $a ( @c ) { ioctl(TTY,$TIOCSTI,$a); select(undef,undef,undef,0.1);} ; print "DONE\n";
Port the following code from Java to Perl with equivalent syntax and logic.
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { ...
use Lingua::EN::Numbers qw(num2en); sub cardinal { my($n) = @_; (my $en = num2en($n)) =~ s/\ and|,//g; $en; } sub magic { my($int) = @_; my $str; while () { $str .= cardinal($int) . " is "; if ($int == 4) { $str .= "magic.\n"; last } else { ...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees0...
use ntheory qw(todigits); use Math::Complex; $sides = 5; $order = 5; $dim = 250; $scale = ( 3 - 5**.5 ) / 2; push @orders, ((1 - $scale) * $dim) * $scale ** $_ for 0..$order-1; open $fh, '>', 'sierpinski_pentagon.svg'; print $fh qq|<svg height="@{[$dim*2]}" width="@{[$dim*2]}" style="fill:blue" version="1.1" xmlns=...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", ...
use v5.36.0; no warnings 'uninitialized'; use List::Util qw(sum min); $source = <<'END'; ............................................................ .. .. .. .. .... .... .... .... .... .... .... .... .. .. .. .. ............................................................ END for $line (split "\n", $source) { p...
Translate the given Java code snippet into Perl without altering its behavior.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().repl...
sub rnd($) { int(rand(shift)) } sub empties { grep !$_[0][$_], 0 .. 7 } sub chess960 { my @s = (undef) x 8; @s[2*rnd(4), 1 + 2*rnd(4)] = qw/B B/; for (qw/Q N N/) { my @idx = empties \@s; $s[$idx[rnd(@idx)]] = $_; } @s[empties \@s] = qw/R K R/; @s } print "@{[chess960]}\n" for 0 .. 10;
Please provide an equivalent version of this Java code in Perl.
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ...
use strict; use warnings; use feature 'say'; sub decode_UPC { my($line) = @_; my(%pattern_to_digit_1,%pattern_to_digit_2,@patterns1,@patterns2,@digits,$sum); for my $p (' push @patterns1, $p; push @patterns2, $p =~ tr/ } $pattern_to_digit_1{$patterns1[$_]} = $_ for 0..$ $pa...
Please provide an equivalent version of this Java code in Perl.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class WriteToWindowsEventLog { public static void main(String[] args) throws IOException...
use strict; use warnings; use Win32::EventLog; my $handle = Win32::EventLog->new("Application"); my $event = { Computer => $ENV{COMPUTERNAME}, Source => 'Rosettacode', EventType => EVENTLOG_INFORMATION_TYPE, Category => 'test', EventID => 0, Data => 'a test for rosettacode', Strings => 'a string...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.util.HashMap; import java.util.Map; public class SpellingOfOrdinalNumbers { public static void main(String[] args) { for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) { System.out.printf("%d = %s%n", test, toOrdinal(test)); ...
use Lingua::EN::Numbers 'num2en_ordinal'; printf "%16s : %s\n", $_, num2en_ordinal(0+$_) for <1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 '00123.0' 1.23e2 '1.23e2'>;
Keep all operations the same but rewrite the snippet in Perl.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4...
sub parse_v4 { my ($ip, $port) = @_; my @quad = split(/\./, $ip); return unless @quad == 4; for (@quad) { return if ($_ > 255) } if (!length $port) { $port = -1 } elsif ($port =~ /^(\d+)$/) { $port = $1 } else { return } my $h = join '' => map(sprintf("%02x", $_), @quad); return $...
Translate this program into Perl but keep the logic exactly as in Java.
import java.util.*; import java.awt.geom.*; public class LineCircleIntersection { public static void main(String[] args) { try { demo(); } catch (Exception e) { e.printStackTrace(); } } private static void demo() throws NoninvertibleTransformException { ...
use strict; use warnings; use feature 'say'; use List::Util 'sum'; sub find_intersection { my($P1, $P2, $center, $radius) = @_; my @d = ($$P2[0] - $$P1[0], $$P2[1] - $$P1[1]); my @f = ($$P1[0] - $$center[0], $$P1[1] - $$center[1]); my $a = sum map { $_**2 } @d; my $b = 2 * ($f[0]*$d[0] + $f[1]*$...
Rewrite the snippet below in Perl so it works the same as the original Java code.
int counter = 100; void setup(){ size(1000,1000); } void draw(){ for(int i=0;i<20;i++){ fill(counter - 5*i); rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i); } counter++; if(counter > 255) counter = 100; delay(100); }
use utf8; binmode STDOUT, ":utf8"; use Time::HiRes qw(sleep); %r = ('tl' => qw<┌>, 'tr' => qw<┐>, 'h' => qw<─>, 'v' => qw<│>, 'bl' => qw<└>, 'br' => qw<┘>); @colors = ("\e[1;31m", "\e[1;32m", "\e[1;33m", "\e[1;34m", "\e[1;35m", "\e[1;36m"); print "\e[?25l"; $SIG{INT} = sub { print "\e[0H\e[0J\e[?25h"; exit; }; wh...
Write a version of this Java function in Perl with identical behavior.
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[...
use strict; use warnings; $_ = do { local $/; <DATA> }; s/./$&$&/g; my $w = /\n/ && $-[0]; my $wd = 3 * $w + 1; my $wr = 2 * $w + 8; my $wl = 2 * $w - 8; place($_, '00'); die "No solution\n"; sub place { (local $_, my $last) = @_; (my $new = $last)++; /$last.{10}(?=00)/...
Write the same algorithm in Perl as shown in this Java implementation.
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[...
use strict; use warnings; $_ = do { local $/; <DATA> }; s/./$&$&/g; my $w = /\n/ && $-[0]; my $wd = 3 * $w + 1; my $wr = 2 * $w + 8; my $wl = 2 * $w - 8; place($_, '00'); die "No solution\n"; sub place { (local $_, my $last) = @_; (my $new = $last)++; /$last.{10}(?=00)/...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.util.*; public class Numbrix { final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00...
use strict; use warnings; $_ = <<END; 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 END my $gap = /.\n/ * $-[0]; print;...
Change the following Java code into Perl without altering its purpose.
import java.util.*; public class Numbrix { final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00...
use strict; use warnings; $_ = <<END; 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 END my $gap = /.\n/ * $-[0]; print;...
Maintain the same structure and functionality when rewriting this code in Perl.
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; public class ChemicalCalculator { private static final Map<String, Double> atomicMass = new HashMap<>(); static { atomicMass.put("H", 1.008); atomicMass.put("He", 4.002602); atomicMas...
use strict; use warnings; use List::Util; use Parse::RecDescent; my $g = Parse::RecDescent->new(<<'EOG'); { my %atomic_weight = <H 1.008 C 12.011 O 15.999 Na 22.99 S 32.06> } weight : compound { $item[1] } compound : group(s) { List::Util::sum( @{$item[1]} ) } group : element /\d+/...
Write the same code in Perl as shown below in Java.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
sub ev {my $exp = shift; $exp =~ tr {0-9.+-/*()} {}cd; return ev_ast(astize($exp));} {my $balanced_paren_regex; $balanced_paren_regex = qr {\( ( [^()]+ | (??{$balanced_paren_regex}) )+ \)}x; sub astize {my $exp = shift; $exp =~ /[^0-9.]/ or return $exp; ...
Port the provided Java code into Perl while preserving the original functionality.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
sub ev {my $exp = shift; $exp =~ tr {0-9.+-/*()} {}cd; return ev_ast(astize($exp));} {my $balanced_paren_regex; $balanced_paren_regex = qr {\( ( [^()]+ | (??{$balanced_paren_regex}) )+ \)}x; sub astize {my $exp = shift; $exp =~ /[^0-9.]/ or return $exp; ...
Translate the given Java code snippet into Perl without altering its behavior.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; ...
use strict; use warnings; use SVG; use List::Util qw(max min); use constant pi => 2 * atan2(1, 0); my $rule = 'XF+F+XF--F--XF+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, spri...
Translate this program into Perl but keep the logic exactly as in Java.
import java.io.*; public class SierpinskiCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) { SierpinskiCurve s = new SierpinskiCurve(writer); s.currentAngle = 45; s.currentX = 5; ...
use strict; use warnings; use SVG; use List::Util qw(max min); use constant pi => 2 * atan2(1, 0); my $rule = 'XF+F+XF--F--XF+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, spri...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup...
use strict; use warnings; sub backup { my($filepath,$limit,$ext) = @_; my $abs = readlink $filepath // $filepath; for my $bnum (reverse 1 .. $limit-1) { rename "$abs$ext$bnum", "$abs$ext" . ++$bnum if -e "$abs$ext$bnum"; } if (-e $abs) { if ($limit > 0) { my $orig = $a...
Produce a functionally identical Perl code for the snippet given in Java.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class FixCodeTags { public static void main(String[] args) { String sourcefile=args[0]; String convertedfile=args[1]; convert(sourcefile,convertedfile); } static String[] languages = {"abap", "a...
my @langs = qw(ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart visualfoxpro mirc make javascript cpp sdlbasic...
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.util.Map; import java.util.Random; public class Game { private static final Map<Integer, Integer> snl = Map.ofEntries( Map.entry(4, 14), Map.entry(9, 31), Map.entry(17, 7), Map.entry(20, 38), Map.entry(28, 84), Map.entry(40, 59), Map.entry(51, 67)...
my %snl =( 4, 14, 9, 31, 17, 7, 20, 38, 28, 84, 40, 59, 51, 67, 54, 34, 62, 19, 63, 81, 64, 60, 71, 91, 87, 24, 93, 73, 95, 75, 99, 78); @players = (1, 1, 1, 1); while () { for $player (0..$ $turn_count++; turn(\$players[$player], $player + 1, $turn_count); } } sub turn { my($...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.util.Map; import java.util.Random; public class Game { private static final Map<Integer, Integer> snl = Map.ofEntries( Map.entry(4, 14), Map.entry(9, 31), Map.entry(17, 7), Map.entry(20, 38), Map.entry(28, 84), Map.entry(40, 59), Map.entry(51, 67)...
my %snl =( 4, 14, 9, 31, 17, 7, 20, 38, 28, 84, 40, 59, 51, 67, 54, 34, 62, 19, 63, 81, 64, 60, 71, 91, 87, 24, 93, 73, 95, 75, 99, 78); @players = (1, 1, 1, 1); while () { for $player (0..$ $turn_count++; turn(\$players[$player], $player + 1, $turn_count); } } sub turn { my($...
Translate this program into Perl but keep the logic exactly as in Java.
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 ...