Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided Java code into Perl while preserving the original functionality.
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class PisanoPeriod { public static void main(String[] args) { System.out.printf("Print pisano(p^2) for every prime p lower than 15%n"); ...
use strict; use warnings; use feature 'say'; use ntheory qw(primes factor_exp lcm); sub pisano_period_pp { my($a, $b, $n, $k) = (0, 1, $_[0]**$_[1]); while (++$k) { ($a, $b) = ($b, ($a+$b) % $n); return $k if $a == 0 and $b == 1; } } sub pisano_period { (lcm map { pisano_period_pp($$_[...
Write the same algorithm in Perl as shown in this Java implementation.
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str...
use strict; use warnings; use integer; my %variables; tree()->run; sub tree { my $line = <> // die "incomplete tree\n"; (local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line"; /String/ ? bless [$arg =~ tr/""//dr =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ger], $_ : /Identifier|Integer/ ? b...
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str...
use strict; use warnings; use integer; my %variables; tree()->run; sub tree { my $line = <> // die "incomplete tree\n"; (local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line"; /String/ ? bless [$arg =~ tr/""//dr =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ger], $_ : /Identifier|Integer/ ? b...
Keep all operations the same but rewrite the snippet in Perl.
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { ...
use utf8; use List::Util qw(sum); use Math::AnyNum qw(gamma pi); sub p_value :prototype($$) { my ($A, $B) = @_; (@$A > 1 && @$B > 1) || return 1; my $x̄_a = sum(@$A) / @$A; my $x̄_b = sum(@$B) / @$B; my $a_var = sum(map { ($x̄_a - $_)**2 } @$A) / (@$A - 1); my $b_var = sum(map { ($x̄_b - $_)...
Port the following code from Java to Perl with equivalent syntax and logic.
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { ...
use utf8; use List::Util qw(sum); use Math::AnyNum qw(gamma pi); sub p_value :prototype($$) { my ($A, $B) = @_; (@$A > 1 && @$B > 1) || return 1; my $x̄_a = sum(@$A) / @$A; my $x̄_b = sum(@$B) / @$B; my $a_var = sum(map { ($x̄_a - $_)**2 } @$A) / (@$A - 1); my $b_var = sum(map { ($x̄_b - $_)...
Generate an equivalent Perl version of this Java code.
import java.util.HashMap; import java.util.Map; public class FourIsTheNumberOfLetters { public static void main(String[] args) { String [] words = neverEndingSentence(201); System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1); for ( int i = 0 ; i < words.length ; i...
use feature 'state'; use Lingua::EN::Numbers qw(num2en num2en_ordinal); my @sentence = split / /, 'Four is the number of letters in the first word of this sentence, '; sub extend_to { my($last) = @_; state $index = 1; until ($ push @sentence, split ' ', num2en(alpha($sentence[$index])) . ' in the ...
Write the same code in Perl as shown below in Java.
import java.math.BigInteger; import java.util.Arrays; public class FibonacciMatrixExponentiation { public static void main(String[] args) { BigInteger mod = BigInteger.TEN.pow(20); for ( int exp : Arrays.asList(32, 64) ) { System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fi...
use strict; use warnings; use Math::AnyNum qw(:overload fibmod floor); use Math::MatrixLUP; sub fibonacci { my $M = Math::MatrixLUP->new([ [1, 1], [1,0] ]); (@{$M->pow(shift)})[0][1] } for my $n (16, 32) { my $f = fibonacci(2**$n); printf "F(2^$n) = %s ... %s\n", substr($f,0,20), $f % 10**20; } sub...
Convert this Java block to Perl, preserving its control flow and logic.
import java.math.BigInteger; import java.util.Arrays; public class FibonacciMatrixExponentiation { public static void main(String[] args) { BigInteger mod = BigInteger.TEN.pow(20); for ( int exp : Arrays.asList(32, 64) ) { System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fi...
use strict; use warnings; use Math::AnyNum qw(:overload fibmod floor); use Math::MatrixLUP; sub fibonacci { my $M = Math::MatrixLUP->new([ [1, 1], [1,0] ]); (@{$M->pow(shift)})[0][1] } for my $n (16, 32) { my $f = fibonacci(2**$n); printf "F(2^$n) = %s ... %s\n", substr($f,0,20), $f % 10**20; } sub...
Port the provided Java code into Perl while preserving the original functionality.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MinimalStepsDownToOne { public static void main(String[] args) { runTasks(getFunctions1()); runTasks(getFunctions2()); runTasks(getFunctions3()); } private static vo...
use strict; use warnings; no warnings 'recursion'; use List::Util qw( first ); use Data::Dump 'dd'; for ( [ 2000, [2, 3], [1] ], [ 2000, [2, 3], [2] ] ) { my ( $n, $div, $sub ) = @$_; print "\n", '-' x 40, " divisors @$div subtractors @$sub\n"; my ($solve, $max) = minimal( @$_ ); printf "%4d takes %s step...
Convert this Java block to Perl, preserving its control flow and logic.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Hee...
use strict; use warnings; use Math::AnyNum; sub ramanujan_const { my ($x, $decimals) = @_; $x = Math::AnyNum->new($x); my $prec = (Math::AnyNum->pi * $x->sqrt)/log(10) + $decimals + 1; local $Math::AnyNum::PREC = 4*$prec->round->numify; exp(Math::AnyNum->pi * $x->sqrt)->round(-$decimals)->stringi...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List; public class RamanujanConstant { public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Hee...
use strict; use warnings; use Math::AnyNum; sub ramanujan_const { my ($x, $decimals) = @_; $x = Math::AnyNum->new($x); my $prec = (Math::AnyNum->pi * $x->sqrt)/log(10) + $decimals + 1; local $Math::AnyNum::PREC = 4*$prec->round->numify; exp(Math::AnyNum->pi * $x->sqrt)->round(-$decimals)->stringi...
Keep all operations the same but rewrite the snippet in Perl.
import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SDF { public static HashMap<Character, Integer> countElementOcurrences(char[] array) { HashMap<C...
use strict ; use warnings ; sub mostFreqHashing { my $inputstring = shift ; my $howmany = shift ; my $outputstring ; my %letterfrequencies = findFrequencies ( $inputstring ) ; my @orderedChars = sort { $letterfrequencies{$b} <=> $letterfrequencies{$a} || index( $inputstring , $a ) <=> index ( $in...
Port the provided Java code into Perl while preserving the original functionality.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OneTimePad { public static void main(String[] args) { String...
use strict; use warnings; use Crypt::OTP; use Bytes::Random::Secure qw( random_bytes ); print "Message  : ", my $message = "show me the monKey", "\n"; my $otp = random_bytes(length $message); print "Ord(OTP)  : ", ( map { ord($_).' ' } (split //, $otp) ) , "\n"; my $cipher = OTP( $otp, $message, 1 ); print...
Write the same algorithm in Perl as shown in this Java implementation.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OneTimePad { public static void main(String[] args) { String...
use strict; use warnings; use Crypt::OTP; use Bytes::Random::Secure qw( random_bytes ); print "Message  : ", my $message = "show me the monKey", "\n"; my $otp = random_bytes(length $message); print "Ord(OTP)  : ", ( map { ord($_).' ' } (split //, $otp) ) , "\n"; my $cipher = OTP( $otp, $message, 1 ); print...
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des...
use strict; use warnings; use List::Util qw( uniq ); my $deps = <<END; top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1 END sub before { map { $deps =~ /^$_\b(.+)/m ? before( split ' ', $1...
Generate an equivalent Perl version of this Java code.
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des...
use strict; use warnings; use List::Util qw( uniq ); my $deps = <<END; top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1 END sub before { map { $deps =~ /^$_\b(.+)/m ? before( split ' ', $1...
Ensure the translated Perl code behaves exactly like the original Java snippet.
size(1000,1000); surface.setTitle("Sunflower..."); int iter = 3000; float factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5; float x = width/2.0, y = height/2.0; double maxRad = pow(iter,factor)/iter; int i; background(#add8e6); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; if(r/maxRad < diskRatio){ strok...
use Game.SDL2; use Game.Framework; class Test { @framework : GameFramework; @colors : Color[]; function : Main(args : String[]) ~ Nil { Test->New()->Run(); } New() { @framework := GameFramework->New(GameConsts->SCREEN_WIDTH, GameConsts->SCREEN_HEIGHT, "Test"); @framework->SetClearColor(Colo...
Write the same code in Perl as shown below in Java.
import java.util.*; public class PracticalNumbers { public static void main(String[] args) { final int from = 1; final int to = 333; List<Integer> practical = new ArrayList<>(); for (int i = from; i <= to; ++i) { if (isPractical(i)) practical.add(i); ...
use strict; use warnings; use feature 'say'; use enum <False True>; use ntheory <divisors vecextract>; use List::AllUtils <sum uniq firstidx>; sub proper_divisors { return 1 if 0 == (my $n = shift); my @d = divisors($n); pop @d; @d } sub powerset_sums { uniq map { sum vecextract(\@_,$_) } 1..2**@_-1 } sub is...
Translate the given Java code snippet into Perl without altering its behavior.
import java.io.File; import java.util.*; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toCollection; public class TransportationProblem { private static int[] demand; private static int[] supply; private static double[][] costs; private static Shipment[][] matrix; ...
use strict; use warnings; use feature 'say'; use List::AllUtils qw( max_by nsort_by min ); my $data = <<END; A=20 B=30 C=10 S=25 T=35 AS=3 BS=5 CS=7 CT=3 BT=2 CT=5 END my $table = sprintf +('%4s' x 4 . "\n") x 3, map {my $t = $_; map "$_$t", '', 'A' .. 'C' } '' , 'S' .. 'T'; my ($cost, %assign) = (0); while( $data...
Rewrite the snippet below in Perl so it works the same as the original Java code.
import java.awt.*; import java.util.List; import java.awt.geom.Path2D; import java.util.*; import javax.swing.*; import static java.lang.Math.*; import static java.util.stream.Collectors.toList; public class PenroseTiling extends JPanel { class Tile { double x, y, angle, size; Type type; ...
use constant pi => 2 * atan2(1, 0); %rules = ( A => '', M => 'OA++PA----NA[-OA----MA]++', N => '+OA--PA[---MA--NA]+', O => '-MA++NA[+++OA++PA]-', P => '--OA++++MA[+PA++++NA]--NA' ); $penrose = '[N]++[N]++[N]++[N]++[N]'; $penrose =~ s/([AMNOP])/$rules{$1}/eg for 1..4; ($x, $y) = (160, 160); $thet...
Keep all operations the same but rewrite the snippet in Perl.
import java.math.BigDecimal; public class GeneralisedFloatingPointAddition { public static void main(String[] args) { BigDecimal oneExp72 = new BigDecimal("1E72"); for ( int i = 0 ; i <= 21+7 ; i++ ) { String s = "12345679"; for ( int j = 0 ; j < i ; j++ ) { ...
use strict; use warnings; use Math::Decimal qw(dec_add dec_mul_pow10); my $e = 63; for my $n (-7..21) { my $num = '12345679' . '012345679' x ($n+7); my $sum = dec_mul_pow10(1, $e); $sum = dec_add($sum, dec_mul_pow10($num,$e)) for 1..81; printf "$n:%s ", 10**72 == $sum ? 'Y' : 'N'; $e -= 9; }
Translate the given Java code snippet into Perl without altering its behavior.
import java.math.BigDecimal; public class GeneralisedFloatingPointAddition { public static void main(String[] args) { BigDecimal oneExp72 = new BigDecimal("1E72"); for ( int i = 0 ; i <= 21+7 ; i++ ) { String s = "12345679"; for ( int j = 0 ; j < i ; j++ ) { ...
use strict; use warnings; use Math::Decimal qw(dec_add dec_mul_pow10); my $e = 63; for my $n (-7..21) { my $num = '12345679' . '012345679' x ($n+7); my $sum = dec_mul_pow10(1, $e); $sum = dec_add($sum, dec_mul_pow10($num,$e)) for 1..81; printf "$n:%s ", 10**72 == $sum ? 'Y' : 'N'; $e -= 9; }
Ensure the translated Perl code behaves exactly like the original Java snippet.
package railwaycircuit; import static java.util.Arrays.stream; import java.util.*; import static java.util.stream.IntStream.range; public class RailwayCircuit { final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0; static String normalize(int[] tracks) { char[] a = new char[tracks.length]; for...
use strict; use warnings; use feature 'say'; use experimental 'signatures'; use List::Util qw(sum); use ntheory 'todigits'; { package Point; use Class::Struct; struct( x => '$', y => '$',); } use constant pi => 2 * atan2(1, 0); use enum qw(False True); my @twelvesteps = map { Point->new( x => sin(pi * $_...
Keep all operations the same but rewrite the snippet in Perl.
import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import...
use DBI; sub connect_db { my ($dbname, $host, $user, $pass) = @_; my $db = DBI->connect("dbi:mysql:$dbname:$host", $user, $pass) or die $DBI::errstr; $db->{RaiseError} = 1; $db } sub create_user { my ($db, $user, $pass) = @_; my $salt = pack "C*", map {int rand 256} 1..16; $d...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numb...
use 5.020; use ntheory qw(is_square_free); use experimental qw(signatures); use Math::AnyNum qw(:overload idiv iroot ipow is_coprime); sub powerful_numbers ($n, $k = 2) { my @powerful; sub ($m, $r) { if ($r < $k) { push @powerful, $m; return; } for my $v (1 .. ...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numb...
use 5.020; use ntheory qw(is_square_free); use experimental qw(signatures); use Math::AnyNum qw(:overload idiv iroot ipow is_coprime); sub powerful_numbers ($n, $k = 2) { my @powerful; sub ($m, $r) { if ($r < $k) { push @powerful, $m; return; } for my $v (1 .. ...
Ensure the translated Perl code behaves exactly like the original Java snippet.
import java.io.File; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; public class Copypasta { public static void fatal_error(String errtext) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); StackTraceElement main = stack[stack.length - 1]; String mainClas...
use strict; use warnings; use feature 'say'; use Path::Tiny; sub CopyPasta { my($code) = @_; my @code = split /\n/, $code =~ s/\s*\n+\s*/\n/gr; return "Program never ends!" unless grep { $_ eq 'Pasta!' } @code; my @cb; my $PC = 0; while (1) { if ($code[$PC] eq 'Copy') { ...
Generate a Perl translation of this Java snippet without changing its computational steps.
int abscissae[]={171,185,202,202,328,208,241,164,69,139,72,168}; int ordinates[] = {171,111,109,189 ,160,254 ,330 ,252,278 ,208 ,148 ,172}; void setup() { size(450, 450); background(255); smooth(); noFill(); stroke(0); beginShape(); for(int i=0;i<abscissae.length;i++){ curveVertex(abscissae[i],...
use strict; use warnings; use Class::Struct; use Cairo; { package Line; struct( A => '@', B => '@'); } my ($WIDTH, $HEIGHT, $W_LINE, $CURVE_F, $DETACHED, $OUTPUT ) = ( 400, 400, 2, 0.25, 0, 'run/b-spline.png' ); my @pt = ( [171, 171], [185, 111], [202, 109], [20...
Keep all operations the same but rewrite the snippet in Perl.
int abscissae[]={171,185,202,202,328,208,241,164,69,139,72,168}; int ordinates[] = {171,111,109,189 ,160,254 ,330 ,252,278 ,208 ,148 ,172}; void setup() { size(450, 450); background(255); smooth(); noFill(); stroke(0); beginShape(); for(int i=0;i<abscissae.length;i++){ curveVertex(abscissae[i],...
use strict; use warnings; use Class::Struct; use Cairo; { package Line; struct( A => '@', B => '@'); } my ($WIDTH, $HEIGHT, $W_LINE, $CURVE_F, $DETACHED, $OUTPUT ) = ( 400, 400, 2, 0.25, 0, 'run/b-spline.png' ); my @pt = ( [171, 171], [185, 111], [202, 109], [20...
Generate a Perl translation of this Java snippet without changing its computational steps.
package pentominotiling; import java.util.*; public class PentominoTiling { static final char[] symbols = "FILNPTUVWXYZ-".toCharArray(); static final Random rand = new Random(); static final int nRows = 8; static final int nCols = 8; static final int blank = 12; static int[][] grid = new in...
use strict; use warnings; use feature 'bitwise'; my $size = shift // 8; sub rotate { local $_ = shift; my $ans = ''; $ans .= "\n" while s/.$/$ans .= $&; ''/gem; $ans; } sub topattern { local $_ = shift; s/.+/ $& . ' ' x ($size - length $&)/ge; s/^\s+|\s+\z//g; [ tr/ \nA-Z/.. /r, lc tr/ \n/\0/r...
Produce a language-to-language conversion: from PHP to Tcl, same semantics.
class MyException extends Exception { }
package require Tcl 8.5 proc e {args} { error "error message" "error message for stack trace" {errorCode list} } proc f {} { if {[catch {e 1 2 3 4} errMsg options] != 0} { return -options $options $errMsg } } f
Port the following code from PHP to Tcl with equivalent syntax and logic.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwi...
proc choose4 {} { set digits {} foreach x {1 2 3 4} {lappend digits [expr {int(1+rand()*9)}]} return [lsort $digits] } proc welcome digits { puts [string trim " The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possibl...
Generate a Tcl translation of this PHP snippet without changing its computational steps.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwi...
proc choose4 {} { set digits {} foreach x {1 2 3 4} {lappend digits [expr {int(1+rand()*9)}]} return [lsort $digits] } proc welcome digits { puts [string trim " The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possibl...
Change the programming language of this snippet from PHP to Tcl without modifying what it does.
define("PI", 3.14159265358); define("MSG", "Hello World");
proc constant {varName {value ""}} { upvar 1 $varName var if {[llength [info frame 0]] == 2} {set value $var} else {set var $value} trace add variable var write [list apply {{val v1 v2 op} { upvar 1 $v1 var set var $val; return -code error "immutable" }} $value] }
Generate a Tcl translation of this PHP snippet without changing its computational steps.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
proc countSubstrings {haystack needle} { regexp -all ***=$needle $haystack } puts [countSubstrings "the three truths" "th"] puts [countSubstrings "ababababab" "abab"] puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]
Keep all operations the same but rewrite the snippet in Tcl.
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0)...
package require Tk set SIZE 800 set SCALE 4.0 set BRANCHES 14 set ROTATION_SCALE 0.85 set INITIAL_LENGTH 50.0 proc draw_tree {w x y dx dy size theta depth} { global SCALE ROTATION_SCALE $w create line $x $y [expr {$x + $dx*$size}] [expr {$y + $dy*$size}] if {[incr depth -1] >= 0} { set x [expr {$x + $dx*...
Maintain the same structure and functionality when rewriting this code in Tcl.
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player ....
package require Tcl 8.5 proc getHumanMove {} { while 1 { puts -nonewline "Your move? \[R\]ock, \[P\]aper, \[S\]cissors: " flush stdout gets stdin line if {[eof stdin]} { puts "\nBye!" exit } set len [string length $line] foreach play {0 1 2} name {"rock" "paper" "scissors"} { if {...
Ensure the translated Tcl code behaves exactly like the original PHP snippet.
<?php $conf = file_get_contents('parse-conf-file.txt'); $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf); $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[]...
proc readConfig {filename {defaults {}}} { global cfg set f [open $filename] set contents [read $f] close $f foreach {var defaultValue} $defaults { set cfg($var) $defaultValue } foreach line [split $contents "\n"] { set line [string trim $line] if {[string match " if {...
Write a version of this PHP function in Tcl with identical behavior.
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
set dog "Benjamin" set Dog "Samba" set DOG "Bernie" puts "The three dogs are named $dog, $Dog and $DOG"
Write a version of this PHP function in Tcl with identical behavior.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ...
proc appendCmd {word} { set candidates [lsearch -inline -all -nocase -glob $::cmds "${word}*"] foreach cand $candidates { if {[string length $word] >= $::minLen($cand)} { lappend ::result [string toupper $cand] return -code continue } } } set cmds {Add ALTer BAckup Bottom CAp...
Convert this PHP snippet to Tcl and keep its semantics consistent.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ...
proc appendCmd {word} { set candidates [lsearch -inline -all -nocase -glob $::cmds "${word}*"] foreach cand $candidates { if {[string length $word] >= $::minLen($cand)} { lappend ::result [string toupper $cand] return -code continue } } } set cmds {Add ALTer BAckup Bottom CAp...
Rewrite the snippet below in Tcl so it works the same as the original PHP code.
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
package require Tcl 8.5 proc stoogesort {L {i 0} {j -42}} { if {$j == -42} { set j [expr {[llength $L]-1}] } set Li [lindex $L $i] set Lj [lindex $L $j] if {$Lj < $Li} { lset L $i $Lj lset L $j $Li } if {$j-$i > 1} { set t [expr {($j-$i+1)/3}] set L [stoogesort ...
Write the same algorithm in Tcl as shown in this PHP implementation.
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $ar...
package require Tcl 8.5 proc shellsort {m} { set len [llength $m] set inc [expr {$len / 2}] while {$inc > 0} { for {set i $inc} {$i < $len} {incr i} { set j $i set temp [lindex $m $i] while {$j >= $inc && [set val [lindex $m [expr {$j - $inc}]]] > $temp} { ...
Convert this PHP snippet to Tcl and keep its semantics consistent.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
proc getNthLineFromFile {filename n} { set f [open $filename] while {[incr n -1] > 0} { if {[gets $f line] < 0} { close $f error "no such line" } } close $f return $line } puts [getNthLineFromFile example.txt 7]
Convert this PHP snippet to Tcl and keep its semantics consistent.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
proc getNthLineFromFile {filename n} { set f [open $filename] while {[incr n -1] > 0} { if {[gets $f line] < 0} { close $f error "no such line" } } close $f return $line } puts [getNthLineFromFile example.txt 7]
Write the same algorithm in Tcl as shown in this PHP implementation.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
proc urlEncode {str} { set uStr [encoding convertto utf-8 $str] set chRE {[^-A-Za-z0-9._~\n]}; set replacement {%[format "%02X" [scan "\\\0" "%c"]]} return [string map {"\n" "%0A"} [subst [regsub -all $chRE $uStr $replacement]]] }
Generate a Tcl translation of this PHP snippet without changing its computational steps.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
proc urlEncode {str} { set uStr [encoding convertto utf-8 $str] set chRE {[^-A-Za-z0-9._~\n]}; set replacement {%[format "%02X" [scan "\\\0" "%c"]]} return [string map {"\n" "%0A"} [subst [regsub -all $chRE $uStr $replacement]]] }
Please provide an equivalent version of this PHP code in Tcl.
<?php function f($n) { return sqrt(abs($n)) + 5 * $n * $n * $n; } $sArray = []; echo "Enter 11 numbers.\n"; for ($i = 0; $i <= 10; $i++) { echo $i + 1, " - Enter number: "; array_push($sArray, (float)fgets(STDIN)); } echo PHP_EOL; $sArray = array_reverse($sArray); foreach ($sArray as $s) { $r = ...
proc f {x} {expr {abs($x)**0.5 + 5*$x**3}} proc overflow {y} {expr {$y > 400}} fconfigure stdout -buffering none for {set n 1} {$n <= 11} {incr n} { puts -nonewline "number ${n}: " lappend S [scan [gets stdin] "%f"] } foreach x [lreverse $S] { set result [f $x] if {[overflow $result]} { puts "${x}...
Keep all operations the same but rewrite the snippet in Tcl.
$odd = function ($prev) use ( &$odd ) { $a = fgetc(STDIN); if (!ctype_alpha($a)) { $prev(); fwrite(STDOUT, $a); return $a != '.'; } $clos = function () use ($a , $prev) { fwrite(STDOUT, $a); $prev(); }; return $odd($clos); }; $even = function () { while (true) { $c = fgetc(STDIN); fwrite(STDOUT, $c...
package require Tcl 8.6 proc fwd c { expr {[string is alpha $c] ? "[fwd [yield f][puts -nonewline $c]]" : $c} } proc rev c { expr {[string is alpha $c] ? "[rev [yield r]][puts -nonewline $c]" : $c} } coroutine f while 1 {puts -nonewline [fwd [yield r]]} coroutine r while 1 {puts -nonewline [rev [yield f]]} for...
Port the following code from PHP to Tcl with equivalent syntax and logic.
<?php function is_describing($number) { foreach (str_split((int) $number) as $place => $value) { if (substr_count($number, $place) != $value) { return false; } } return true; } for ($i = 0; $i <= 50000000; $i += 10) { if (is_describing($i)) { echo $i . PHP_EOL;...
package require Tcl 8.5 proc isSelfDescribing num { set digits [split $num ""] set len [llength $digits] set count [lrepeat $len 0] foreach d $digits { if {$d >= $len} {return false} lset count $d [expr {[lindex $count $d] + 1}] } foreach d $digits c $count {if {$c != $d} {return false}} r...
Preserve the algorithm and functionality while converting the code from PHP to Tcl.
<?php foreach(file("unixdict.txt") as $w) echo (strstr($w, "the") && strlen(trim($w)) > 11) ? $w : "";
foreach w [read [open unixdict.txt]] { if {[string first the $w] != -1 && [string length $w] > 11} { puts $w } }
Change the programming language of this snippet from PHP to Tcl without modifying what it does.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
set hereDocExample { In Tcl, the {curly brace} notation is strictly a here-document style notation as it permits arbitrary content inside it *except* for an unbalanced brace. That is typically not a problem as seen in reality, as almost all content that might be placed in a here-doc is either brace-free or balanced. T...
Produce a functionally identical Tcl code for the snippet given in PHP.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
set hereDocExample { In Tcl, the {curly brace} notation is strictly a here-document style notation as it permits arbitrary content inside it *except* for an unbalanced brace. That is typically not a problem as seen in reality, as almost all content that might be placed in a here-doc is either brace-free or balanced. T...
Translate the given PHP code snippet into Tcl without altering its behavior.
<?php $game = new Game(); while(true) { $game->cycle(); } class Game { private $field; private $fieldSize; private $command; private $error; private $lastIndexX, $lastIndexY; private $score; private $finishScore; function __construct() { $this->field = array(); $this->fieldSize = 4; $this->finishS...
package require Tcl 8.5 package require struct::matrix package require struct::list set size 4 proc forcells {cellList varName1 varName2 cellVarName script} { upvar $varName1 i upvar $varName2 j upvar $cellVarName c foreach cell $cellList { set i [lindex $cell 0] set...
Generate an equivalent Tcl version of this PHP code.
while(1) echo "SPAM\n";
while true { puts SPAM } for {} 1 {} { puts SPAM }
Generate an equivalent Tcl version of this PHP code.
function multiply( $a, $b ) { return $a * $b; }
proc multiply { arg1 arg2 } { return [expr {$arg1 * $arg2}] }
Write the same code in Tcl as shown below in PHP.
$server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com"; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } e...
package require ftp set conn [::ftp::Open kernel.org anonymous "" -mode passive] ::ftp::Cd $conn /pub/linux/kernel foreach line [ftp::NList $conn] { puts $line } ::ftp::Type $conn binary ::ftp::Get $conn README README
Change the following PHP code into Tcl without altering its purpose.
<?php $db = new SQLite3(':memory:'); $db->exec(" CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) "); ?>
package require sqlite3 sqlite3 db address.db db eval { CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) }
Ensure the translated Tcl code behaves exactly like the original PHP snippet.
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) ...
package require Tcl 8.5 proc beadsort numList { if {![llength $numList]} return foreach n $numList { for {set i 0} {$i<$n} {incr i} { dict incr vals $i } } foreach n [dict values $vals] { for {set i 0} {$i<$n} {incr i} { dict incr result $i } } dict values $res...
Please provide an equivalent version of this PHP code in Tcl.
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __c...
package require Tcl 8.5 namespace eval playing_cards { variable deck variable suits {\u2663 \u2662 \u2661 \u2660} variable pips {2 3 4 5 6 7 8 9 10 J Q K A} proc new_deck {} { variable deck set deck [list] for {set i 0} {$i < 52} {incr i} { lappend deck $i ...
Rewrite the snippet below in Tcl so it works the same as the original PHP code.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
set deepCopy [string range ${valueToCopy}x 0 end-1]
Maintain the same structure and functionality when rewriting this code in Tcl.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
set deepCopy [string range ${valueToCopy}x 0 end-1]
Rewrite the snippet below in Tcl so it works the same as the original PHP code.
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) ...
package require Tcl 8.5 package require struct::list proc inorder {list} {::tcl::mathop::<= {*}$list} proc permutationsort {list} { while { ! [inorder $list]} { set list [struct::list nextperm $list] } return $list }
Generate a Tcl translation of this PHP snippet without changing its computational steps.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
proc main {args} { puts "Directory: [pwd]" puts "Program: $::argv0" puts "Number of args: [llength $args]" foreach arg $args {puts "Arg: $arg"} } if {$::argv0 eq [info script]} { main {*}$::argv }
Translate this program into Tcl but keep the logic exactly as in PHP.
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
proc lastSundays {{year ""}} { if {$year eq ""} { set year [clock format [clock seconds] -gmt 1 -format "%Y"] } foreach month {2 3 4 5 6 7 8 9 10 11 12 13} { set d [clock add [clock scan "$month/1/$year" -gmt 1] -1 day] while {[clock format $d -gmt 1 -format "%u"] != 7} { set d [clock add $d -1 day]...
Generate an equivalent Tcl version of this PHP code.
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
proc lastSundays {{year ""}} { if {$year eq ""} { set year [clock format [clock seconds] -gmt 1 -format "%Y"] } foreach month {2 3 4 5 6 7 8 9 10 11 12 13} { set d [clock add [clock scan "$month/1/$year" -gmt 1] -1 day] while {[clock format $d -gmt 1 -format "%u"] != 7} { set d [clock add $d -1 day]...
Translate this program into Tcl but keep the logic exactly as in PHP.
<?php class Node { public $val; public $back = NULL; } function lis($n) { $pileTops = array(); foreach ($n as $x) { $low = 0; $high = count($pileTops)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($pileTops[$mid]->val >= $x) $...
package require Tcl 8.6 proc longestIncreasingSubsequence {sequence} { set subseq [list 1 [lindex $sequence 0]] foreach value $sequence { set max {} foreach {len item} $subseq { if {[lindex $item end] < $value} { if {[llength [lappend item $value]] > [llength $max]} { set max $item } ...
Change the following PHP code into Tcl without altering its purpose.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
puts "Enter a variable name:" gets stdin varname set $varname 42 puts "I have set variable $varname to [set $varname]"
Convert this PHP snippet to Tcl and keep its semantics consistent.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
proc eval_twice {func a b} { set x $a set 1st [expr $func] set x $b set 2nd [expr $func] expr {$2nd - $1st} } puts [eval_twice {2 ** $x} 3 5] ;
Preserve the algorithm and functionality while converting the code from PHP to Tcl.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
proc eval_twice {func a b} { set x $a set 1st [expr $func] set x $b set 2nd [expr $func] expr {$2nd - $1st} } puts [eval_twice {2 ** $x} 3 5] ;
Produce a language-to-language conversion: from PHP to Tcl, same semantics.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
set four 4 set result1 [eval "expr {$four + 5}"] ; set result2 [eval [list expr [list $four + 5]]] ;
Generate a Tcl translation of this PHP snippet without changing its computational steps.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
set four 4 set result1 [eval "expr {$four + 5}"] ; set result2 [eval [list expr [list $four + 5]]] ;
Port the following code from PHP to Tcl with equivalent syntax and logic.
function getitem($s,$depth=0) { $out = ['']; while ($s) { $c = $s[0]; if ($depth && ($c == ',' || $c == '}')) { return [$out, $s]; } if ($c == '{') { $x = getgroup(substr($s, 1), $depth + 1); if($x) { $tmp = []; ...
package require Tcl 8.6 proc combine {cases1 cases2 {insert ""}} { set result {} foreach c1 $cases1 { foreach c2 $cases2 { lappend result $c1$insert$c2 } } return $result } proc expand {string *expvar} { upvar 1 ${*expvar} expanded set a {} set result {} set depth 0 foreach t...
Generate an equivalent Tcl version of this PHP code.
$img = imagegrabscreen(); $color = imagecolorat($im, 10, 50); imagedestroy($im);
package require Tcl 8.5 package require Tk proc grabScreen {image} { set pipe [open {|xwd -root -silent | convert xwd:- ppm:-} rb] $image put [read $pipe] close $pipe } proc getPixelAtPoint {x y} { set buffer [image create photo] grabScreen $buffer set data [$image get $x $y] image delet...
Port the provided PHP code into Tcl while preserving the original functionality.
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
package require ldap set conn [ldap::connect $host $port] ldap::bind $conn $user $password
Can you help me rewrite this code in Tcl instead of PHP, keeping it the same logically?
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
package require WS::Client ::WS::Client::GetAndParseWsdl http://example.com/soap/wsdl ::WS::Client::CreateStubs ExampleService ; set result1 [ExampleService::soapFunc "hello"] set result2 [ExampleService::anotherSoapFunc 34234]
Convert this PHP block to Tcl, preserving its control flow and logic.
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList();...
proc merge {listVar toMerge} { upvar 1 $listVar v set i [set j 0] set out {} while {$i<[llength $v] && $j<[llength $toMerge]} { if {[set a [lindex $v $i]] < [set b [lindex $toMerge $j]]} { lappend out $a incr i } else { lappend out $b incr j } } set v [concat $ou...
Keep all operations the same but rewrite the snippet in Tcl.
<?php $doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>'); $xpath = new DOMXPath($doc); $nodelist = $xpath->query('//item'); $result = $nodelist->item(0); $nodelist = $xpath->query('//price'); for($i = 0; $i < $nodelist->length; $i++) { print $doc->saveXML($nodelist->item($i...
package require tdom set doc [dom parse $xml] set root [$doc documentElement] set allNames [$root selectNodes //name] puts [llength $allNames] ; set firstItem [lindex [$root selectNodes //item] 0] puts [$firstItem @upc] ; foreach node [$root selectNodes //price] { puts [$node text] }
Translate the given PHP code snippet into Tcl without altering its behavior.
<?php $conf = file_get_contents('update-conf-file.txt'); $conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf); $conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf); $conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf); if (preg_match('/^;?\s*(numberofstrawberries)/mi'...
package require Tcl 8.6 oo::class create Config { variable filename contents constructor fileName { set filename $fileName set contents {} try { set f [open $filename] foreach line [split [read $f] \n] { if {[string match " lappend contents $line continue } if {[regexp {^;\W...
Write the same algorithm in Tcl as shown in this PHP implementation.
$key2val = ["A"=>"30", "B"=>"31", "C"=>"32", "D"=>"33", "E"=>"5", "F"=>"34", "G"=>"35", "H"=>"0", "I"=>"36", "J"=>"37", "K"=>"38", "L"=>"2", "M"=>"4", "."=>"78", "N"=>"39", "/"=>"79", "O"=>"1", "0"=>"790", "P"=>"70", "1"=>"791", "Q"=>"71", "2"=>"792", "R"=>"8", "3"=>"793", "S"=>"6", "4"=>"794", ...
package require Tcl 8.6 oo::class create StraddlingCheckerboardCypher { variable encmap decmap constructor table { foreach ch [lindex $table 0] i {"" 0 1 2 3 4 5 6 7 8 9} { if {$ch eq "" && $i ne "" && [lsearch -index 0 $table $i] < 1} { error "bad checkerboard table" } } foreach row $table ...
Translate the given PHP code snippet into Tcl without altering its behavior.
<?php class Example { function foo() { echo "this is foo\n"; } function bar() { echo "this is bar\n"; } function __call($name, $args) { echo "tried to handle unknown method $name\n"; if ($args) echo "it had arguments: ", implode(', ', $args), "\n"; } } $example = new Example(); $exam...
package require TclOO oo::class create Example { method foo {} { puts "this is foo" } method bar {} { puts "this is bar" } } Example create example oo::objdefine example { method unknown {name args} { puts "tried to handle unknown method \"$name\"" if {[llength $ar...
Rewrite the snippet below in Tcl so it works the same as the original PHP code.
<?php function hashJoin($table1, $index1, $table2, $index2) { foreach ($table1 as $s) $h[$s[$index1]][] = $s; foreach ($table2 as $r) foreach ($h[$r[$index2]] as $s) $result[] = array($s, $r); return $result; } $table1 = array(array(27, "Jonah"), array(18, "Alan"), ...
package require Tcl 8.6 proc joinTables {tableA a tableB b} { if {[llength $tableB] < [llength $tableA]} { return [lmap pair [joinTables $tableB $b $tableA $a] { lreverse $pair }] } foreach value $tableA { lappend hashmap([lindex $value $a]) [lreplace $value $a $a] } set result {} ...
Translate this program into Tcl but keep the logic exactly as in PHP.
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array...
proc permutate {values size offset} { set count [llength $values] set arr [list] for {set i 0} {$i < $size} {incr i} { set selector [expr [round [expr $offset / [pow $count $i]]] % $count]; lappend arr [lindex $values $selector] } return $arr } proc permutations {values siz...
Generate a Tcl translation of this PHP snippet without changing its computational steps.
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array...
proc permutate {values size offset} { set count [llength $values] set arr [list] for {set i 0} {$i < $size} {incr i} { set selector [expr [round [expr $offset / [pow $count $i]]] % $count]; lappend arr [lindex $values $selector] } return $arr } proc permutations {values siz...
Ensure the translated Tcl code behaves exactly like the original PHP snippet.
<?php <?php $mac_use_espeak = false; $voice = "espeak"; $statement = 'Hello World!'; $save_file_args = '-w HelloWorld.wav'; // eSpeak args $OS = strtoupper(substr(PHP_OS, 0, 3)); elseif($OS === 'DAR' && $mac_use_espeak == false) { $voice = "say -v 'Victoria'"; $save_file_args = '-o HelloWorl...
exec festival --tts << "This is an example of speech synthesis."
Convert the following code from PHP to Tcl, ensuring the logic remains intact.
<?php define('MINEGRID_WIDTH', 6); define('MINEGRID_HEIGHT', 4); define('MINESWEEPER_NOT_EXPLORED', -1); define('MINESWEEPER_MINE', -2); define('MINESWEEPER_FLAGGED', -3); define('MINESWEEPER_FLAGGED_MINE', -4); define('ACTIVATED_MINE', -5); function check_field($field) { if ($field === MI...
package require Tcl 8.5 fconfigure stdout -buffering none proc makeGrid {n m} { global grid mine unset -nocomplain grid mine set grid(size) [list $n $m] set grid(shown) 0 set grid(marked) 0 for {set j 1} {$j <= $m} {incr j} { for {set i 1} {$i <= $n} {incr i} { set grid($i,$j) . } }...
Generate an equivalent Tcl version of this PHP code.
<? class Foo { function bar(int $x) { } } $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo "$name\n"; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
% info object methods ::oo::class -all -private <cloned> create createWithNamespace destroy eval new unknown variable varname
Port the provided PHP code into Tcl while preserving the original functionality.
<?php class Example { function foo($x) { return 42 + $x; } } $example = new Example(); $name = 'foo'; echo $example->$name(5), "\n"; // prints "47" echo call_user_func(array($example, $name), 5), "\n"; ?>
package require Tcl 8.6 oo::class create Example { method foo {} {return 42} method 1 {s} {puts "fee$s"} method 2 {s} {puts "fie$s"} method 3 {s} {puts "foe$s"} method 4 {s} {puts "fum$s"} } set eg [Example new] set mthd [format "%c%c%c" 102 111 111]; puts [$eg $mthd] for {set i 1} {$i <= 4} {in...
Port the provided PHP code into Tcl while preserving the original functionality.
<?php $l = ldap_connect('ldap.example.com'); ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($l, LDAP_OPT_REFERRALS, false); $bind = ldap_bind($l, 'me@example.com', 'password'); $base = 'dc=example, dc=com'; $criteria = '(&(objectClass=user)(sAMAccountName=username))'; $attributes = array('display...
set Username "TestUser" set Filter "((&objectClass=*)(sAMAccountName=$Username))" set Base "dc=skycityauckland,dc=sceg,dc=com" set Attrs distinguishedName
Rewrite the snippet below in Tcl so it works the same as the original PHP code.
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
% package require Tk 8.6.5 % . configure {-bd -borderwidth} {-borderwidth borderWidth BorderWidth 0 0} {-class class Class Toplevel Tclsh} {-menu menu Menu {} {}} {-relief relief Relief flat flat} {-screen screen Screen {} {}} {-use use Use {} {}} {-background background Background {-container container Container 0...
Change the following PHP code into Tcl without altering its purpose.
function RGBtoHSV($r, $g, $b) { $r = $r/255.; // convert to range 0..1 $g = $g/255.; $b = $b/255.; $cols = array("r" => $r, "g" => $g, "b" => $b); asort($cols, SORT_NUMERIC); $min = key(array_slice($cols, 1)); // "r", "g" or "b" $max = key(array_slice($cols, -1)); // "r", "g" or "b" if($cols[$min] == $cols[$m...
package require crimp package require crimp::pgm proc readPGM {filename} { set f [open $filename rb] set data [read $f] close $f return [crimp read pgm $data] } proc writePGM {filename image} { crimp write 2file pgm-raw $filename $image } proc cannyFilterFile {{inputFile "lena.pgm"} {outputFile "l...
Convert this PHP snippet to Tcl and keep its semantics consistent.
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled t...
proc findURIs {text args} { set URI {(?x) [a-z][-a-z0-9+.]*: (?=[/\w]) (?://[-\w.@:]+)? [-\w.~/%!$&'()*+,;=]* (?:\?[-\w.~%!$&'()*+,;=/?]*)? (?:[ } regexp -inline -all {*}$args -- $URI $text }
Write a version of this PHP function in Tcl with identical behavior.
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled t...
proc findURIs {text args} { set URI {(?x) [a-z][-a-z0-9+.]*: (?=[/\w]) (?://[-\w.@:]+)? [-\w.~/%!$&'()*+,;=]* (?:\?[-\w.~%!$&'()*+,;=/?]*)? (?:[ } regexp -inline -all {*}$args -- $URI $text }
Translate this program into Tcl but keep the logic exactly as in PHP.
function connect_db($database, $db_user, $db_password, $host = 'localhost', $port = NULL, $die = false) { if(!$db_handle = @mysql_connect($host.($port ? ':'.$port : ''), $db_user, $db_password)) { if($die) die("Can't connect to MySQL server:\r\n".mysql_error()); else return false; } if(!@mysql_select_...
package require tdbc proc connect_db {handleName dbname host user pass} { package require tdbc::mysql tdbc::mysql::connection create $handleName -user $user -passwd $pass \ -host $host -database $dbname return $handleName } proc r64k {} { expr int(65536*rand()) } proc create_user {handle use...
Produce a language-to-language conversion: from Go to Swift, same semantics.
package main import "fmt" func jaro(str1, str2 string) float64 { if len(str1) == 0 && len(str2) == 0 { return 1 } if len(str1) == 0 || len(str2) == 0 { return 0 } match_distance := len(str1) if len(str2) > match_distance { match_distance = len(str2) } match_dist...
func jaroWinklerMatch(_ s: String, _ t: String) -> Double { let s_len: Int = s.count let t_len: Int = t.count if s_len == 0 && t_len == 0 { return 1.0 } if s_len == 0 || t_len == 0 { return 0.0 } var match_distance: Int = 0 if s_len == 1 && t_len == 1...
Ensure the translated Swift code behaves exactly like the original Go snippet.
package main import "fmt" func largestProperDivisor(n int) int { for i := 2; i*i <= n; i++ { if n%i == 0 { return n / i } } return 1 } func main() { fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:") fmt.Print(" 1 ") for n := 2; n...
import Foundation func largestProperDivisor(_ n : Int) -> Int? { guard n > 0 else { return nil } if (n & 1) == 0 { return n >> 1 } var p = 3 while p * p <= n { if n % p == 0 { return n / p } p += 2 } return 1 } for n in (1..<101) { ...
Change the following Go code into Swift without altering its purpose.
package main import ( "fmt" "math" ) const CONST = 0x2545F4914F6CDD1D type XorshiftStar struct{ state uint64 } func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} } func (xor *XorshiftStar) seed(state uint64) { xor.state = state } func (xor *XorshiftStar) nextInt() uint32 { ...
import Foundation struct XorshiftStar { private let magic: UInt64 = 0x2545F4914F6CDD1D private var state: UInt64 init(seed: UInt64) { state = seed } mutating func nextInt() -> UInt64 { state ^= state &>> 12 state ^= state &<< 25 state ^= state &>> 27 return (state &* magic) &>> 32 ...
Write a version of this Go function in Swift with identical behavior.
package main import "fmt" func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { f...
import Foundation func equalRisesAndFalls(_ n: Int) -> Bool { var total = 0 var previousDigit = -1 var m = n while m > 0 { let digit = m % 10 m /= 10 if previousDigit > digit { total += 1 } else if previousDigit >= 0 && previousDigit < digit { tot...
Produce a language-to-language conversion: from Go to Swift, same semantics.
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } fu...
import Foundation extension BinaryInteger { @inlinable public var isSelfDescribing: Bool { let stringChars = String(self).map({ String($0) }) let counts = stringChars.reduce(into: [Int: Int](), {res, char in res[Int(char), default: 0] += 1}) for (i, n) in stringChars.enumerated() where counts[i, defau...
Rewrite this program in Swift while keeping its functionality equivalent to the Go version.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string outer: ...
import Foundation func e3(_ word: String) -> Bool { var ecount = 0 for ch in word { switch (ch) { case "a", "A", "i", "I", "o", "O", "u", "U": return false case "e", "E": ecount += 1 default: break } } return ecount > 3 } do {...