Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this PHP snippet to REXX and keep its semantics consistent.
<?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 ...
parse arg yyyy do j=1 for 12 _ = lastDOW('Sunday', j, yyyy) say right(_,4)'-'right(j,2,0)"-"left(word(_,2),2) end exit β”‚ lastDOW: procedure to return the date of the last day-of-week of β”‚ β”‚ ...
Rewrite this program in REXX while keeping its functionality equivalent to the PHP version.
<?php $attributesTotal = 0; $count = 0; while($attributesTotal < 75 || $count < 2) { $attributes = []; foreach(range(0, 5) as $attribute) { $rolls = []; foreach(range(0, 3) as $roll) { $rolls[] = rand(1, 6); } sort($rolls); array_shift...
Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. */ Do try=1 By 1 ge15=0 sum=0 ol='' Do i=1 To 6 rl='' Do j=1 To 4 rl=rl (random(5)+1) End rl=wordsort(rl) ...
Preserve the algorithm and functionality while converting the code from PHP to REXX.
<?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) $...
$.=; $.1= 3 2 6 4 5 1 $.2= 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 do j=1 while $.j\==''; say say ' input: ' $.j call LIS $.j say 'output: ' result end exi...
Change the following PHP code into REXX without altering its purpose.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
parse arg newVar newValue say 'Arguments as they were entered via the command line: ' newVar newValue say call value newVar, newValue say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar)
Port the provided PHP code into REXX while preserving the original functionality.
<?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". ?>
say evalWithX("x**2", 2) say evalWithX("x**2", 3.1415926) ::routine evalWithX use arg expression, x -- X now has the value of the second argument interpret "return" expression
Preserve the algorithm and functionality while converting the code from PHP to REXX.
<?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". ?>
say evalWithX("x**2", 2) say evalWithX("x**2", 3.1415926) ::routine evalWithX use arg expression, x -- X now has the value of the second argument interpret "return" expression
Convert this PHP snippet to REXX and keep its semantics consistent.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
a = .array~of(1, 2, 3) ins = "loop num over a; say num; end" interpret ins
Ensure the translated REXX code behaves exactly like the original PHP snippet.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
a = .array~of(1, 2, 3) ins = "loop num over a; say num; end" interpret ins
Port the following code from PHP to REXX 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 = []; ...
* Brace expansion * 26.07.2016 * s.* holds the set of strings *--------------------------------------------------------------------*/ text.1='{,{,gotta have{ ,\, again\, }}more }cowbell!' text.2='~/{Downloads,Pictures} text.3='It{{em,alic}iz,erat}e{d,}, please. ' text.4='{}} some }{,{\\{ edge, edge} \,}{ cases, {here}...
Preserve the algorithm and functionality while converting the code from PHP to REXX.
$img = imagegrabscreen(); $color = imagecolorat($im, 10, 50); imagedestroy($im);
parse value cursor() with r c . hue=scrRead(r, c, 1, 'A') if hue=='00'x then color= 'black' if hue=='01'x then color= 'darkblue' if hue=='02'x then color= 'darkgreen' if hue=='03'x then color= 'darkturquoise' if hue=='04'x then color= 'darkred' ...
Convert this PHP snippet to REXX and keep its semantics consistent.
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
options replace format comments java crossref symbols binary import org.apache.directory.ldap.client.api.LdapConnection import org.apache.directory.ldap.client.api.LdapNetworkConnection import org.apache.directory.shared.ldap.model.exception.LdapException import org.slf4j.Logger import org.slf4j.LoggerFactory class ...
Port the following code from PHP to REXX with equivalent syntax 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();...
options replace format comments java crossref savelog symbols binary import java.util.List placesList = [String - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - ] lists = [ - placesList - , strandSort(St...
Generate an equivalent REXX version of this PHP code.
<?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...
options replace format comments java symbols binary import javax.xml.parsers. import javax.xml.xpath. import org.w3c.dom. import org.w3c.dom.Node import org.xml.sax. xmlStr = '' - || '<inventory title="OmniCorp Store #45x10^3">' - || ' <section name="health">' - || ' <item upc="123456789" stock="12">' - ...
Translate this program into REXX but keep the logic exactly as in PHP.
<?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'...
parse arg iFID oFID . if iFID=='' | iFID=="," then iFID= 'UPDATECF.TXT' if oFID=='' | oFID=="," then oFID='\TEMP\UPDATECF.$$$' call lineout iFID; call lineout oFID $.=0 call dos 'ERASE' oFID cha...
Rewrite the snippet below in REXX so it works the same as the original PHP code.
$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", ...
parse arg msg if msg='' then msg= 'One night-it was the twentieth of March, 1888-I was returning' say 'plain text=' msg call genCipher 'et aon ris', 'bcdfghjklm', 'pq/uvwxyz.' enc= encrypt(msg); say ' encrypted=' enc dec= decrypt(enc); say...
Produce a functionally identical REXX code for the snippet given in PHP.
<?php class Example { function foo() { echo "this is foo\n"; } function bar() { echo "this is bar\n"; } function __call($name, $args) { echo "tried to handle unknown method $name\n"; if ($args) echo "it had arguments: ", implode(', ', $args), "\n"; } } $example = new Example(); $exam...
u = .unknown~new u~foo(1, 2, 3) ::class unknown ::method unknown use arg name, args say "Unknown method" name "invoked with arguments:" args~tostring('l',', ')
Produce a language-to-language conversion: from PHP to REXX, same semantics.
<?php function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return fal...
do j=1; if \isPrime(j) then iterate r= testMer(j) if r==0 then say right('M'j, 10) "──────── is a Mersenne prime." else say right('M'j, 50) "is composite, a factor:" r end ex...
Change the programming language of this snippet from PHP to REXX without modifying what it does.
<?php function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return fal...
do j=1; if \isPrime(j) then iterate r= testMer(j) if r==0 then say right('M'j, 10) "──────── is a Mersenne prime." else say right('M'j, 50) "is composite, a factor:" r end ex...
Keep all operations the same but rewrite the snippet in REXX.
<?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"), ...
S. = ; R. = S.1 = 27 'Jonah' ; R.1 = "Jonah Whales" S.2 = 18 'Alan' ; R.2 = "Jonah Spiders" S.3 = 28 'Glory' ; R.3 = "Alan Ghosts" S.4 = 18 ...
Please provide an equivalent version of this PHP code in REXX.
<?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...
parse arg things bunch inbetweenChars names call permSets things, bunch, inBetweenChars, names exit p: return word( arg(1), 1) permSets: procedure; parse arg x,y,between,uSy...
Change the programming language of this snippet from PHP to REXX without modifying what it does.
<?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...
parse arg things bunch inbetweenChars names call permSets things, bunch, inBetweenChars, names exit p: return word( arg(1), 1) permSets: procedure; parse arg x,y,between,uSy...
Translate this program into REXX but keep the logic exactly as in PHP.
<?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...
parse arg t if t='' then exit dquote= '"' rate= 1 'NIRCMD' "speak text" dquote t dquote rate
Produce a functionally identical REXX code for the snippet given in PHP.
function perpendicular_distance(array $pt, array $line) { $dx = $line[1][0] - $line[0][0]; $dy = $line[1][1] - $line[0][1]; $mag = sqrt($dx * $dx + $dy * $dy); if ($mag > 0) { $dx /= $mag; $dy /= $mag; } $pvx = $pt[0] - $line[0][0]; $pvy = $pt[1] - $line[0][1]; $pvdot = $dx * $pvx + $dy * $pvy...
parse arg epsilon pts if epsilon='' | epsilon="," then epsilon= 1 if pts='' then pts= '(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)' pts= space(pts) say ' error threshold: ' epsilon say ' points spe...
Keep all operations the same but rewrite the snippet in REXX.
function perpendicular_distance(array $pt, array $line) { $dx = $line[1][0] - $line[0][0]; $dy = $line[1][1] - $line[0][1]; $mag = sqrt($dx * $dx + $dy * $dy); if ($mag > 0) { $dx /= $mag; $dy /= $mag; } $pvx = $pt[0] - $line[0][0]; $pvy = $pt[1] - $line[0][1]; $pvdot = $dx * $pvx + $dy * $pvy...
parse arg epsilon pts if epsilon='' | epsilon="," then epsilon= 1 if pts='' then pts= '(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)' pts= space(pts) say ' error threshold: ' epsilon say ' points spe...
Preserve the algorithm and functionality while converting the code from PHP to REXX.
<?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...
options replace format comments java crossref symbols binary import org.apache.directory.ldap.client.api.LdapConnection import org.apache.directory.ldap.client.api.LdapNetworkConnection import org.apache.directory.shared.ldap.model.cursor.EntryCursor import org.apache.directory.shared.ldap.model.entry.Entry import or...
Translate the given PHP code snippet into REXX without altering its behavior.
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
d.1='' d.2='a23' d.3='101' d.4='123' d.5='12345678901234567890' d.6='abc' d.7='aBc' d.8='1' d.9='0' d.10='Walter' d.11='ABC' d.12='f23' d.13='123' t.1='A' t.2='B' t.3='I' t.4='L' t.5='M' t.6='N' t.7='O' t.8='S' t.9='U' t.10='V' t.11='W' t.12=...
Port the provided PHP code into REXX while preserving the original functionality.
<?php function markovChainTextGenerator($text, $keySize, $maxWords) { $token = array(); $position = 0; $maxPosition = strlen($text); while ($position < $maxPosition) { if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) { $token[] = $matches[1]; $positio...
parse arg ord fin iFID seed . if ord=='' | ord=="," then ord= 3 if fin=='' | fin=="," then fin= 300 if iFID=='' |iFID=="," then iFID='alice_oz.txt' if datatype(seed, 'W') then call random ,,seed sw = linesize() - 1 $= space( linein(iF...
Convert the following code from PHP to REXX, ensuring the logic remains intact.
$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...
$$= '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 the wrong way by...
Port the following code from PHP to REXX with equivalent syntax and logic.
$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...
$$= '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 the wrong way by...
Change the following PHP code into Lua without altering its purpose.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
function countSubstring(s1, s2) return select(2, s1:gsub(s2, "")) end print(countSubstring("the three truths", "th")) print(countSubstring("ababababab", "abab"))
Produce a language-to-language conversion: from PHP to Lua, same semantics.
<?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)...
g, angle = love.graphics, 26 * math.pi / 180 wid, hei = g.getWidth(), g.getHeight() function rotate( x, y, a ) local s, c = math.sin( a ), math.cos( a ) local a, b = x * c - y * s, x * s + y * c return a, b end function branches( a, b, len, ang, dir ) len = len * .76 if len < 5 then return end g.setColor( l...
Rewrite this program in Lua while keeping its functionality equivalent to the PHP version.
<?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 ....
function cpuMove() local totalChance = record.R + record.P + record.S if totalChance == 0 then local choice = math.random(1, 3) if choice == 1 then return "R" end if choice == 2 then return "P" end if choice == 3 then return "S" end end local choice = math.random(1, totalChance) if choic...
Rewrite the snippet below in Lua so it works the same as the original PHP code.
<?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] . '[]...
conf = {} fp = io.open( "conf.txt", "r" ) for line in fp:lines() do line = line:match( "%s*(.+)" ) if line and line:sub( 1, 1 ) ~= "#" and line:sub( 1, 1 ) ~= ";" then option = line:match( "%S+" ):lower() value = line:match( "%S*%s*(.*)" ) if not value then conf[option] = true else if not va...
Transform the following PHP implementation into Lua, maintaining the same output and logic.
<?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";
dog = "Benjamin" Dog = "Samba" DOG = "Bernie" print( "There are three dogs named "..dog..", "..Dog.." and "..DOG.."." )
Rewrite this program in Lua while keeping its functionality equivalent to the PHP version.
$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 ...
#!/usr/bin/lua local list1 = [[ 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 LOWe...
Convert this PHP snippet to Lua 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 ...
#!/usr/bin/lua local list1 = [[ 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 LOWe...
Generate an equivalent Lua version of this 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); } }
local Y = function (f) return (function(x) return x(x) end)(function(x) return f(function(...) return x(x)(...) end) end) end function stoogesort(L, pred) pred = pred or function(a,b) return a < b end Y(function(recurse) return function(i,j) if pred(L[j], L[i]) then L[j],L[i] = L[i],L[j] ...
Maintain the same structure and functionality when rewriting this code in Lua.
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...
function shellsort( a ) local inc = math.ceil( #a / 2 ) while inc > 0 do for i = inc, #a do local tmp = a[i] local j = i while j > inc and a[j-inc] > tmp do a[j] = a[j-inc] j = j - inc end a[j] = tmp end ...
Generate an equivalent Lua version of this PHP code.
<?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...
function fileLine (lineNum, fileName) local count = 0 for line in io.lines(fileName) do count = count + 1 if count == lineNum then return line end end error(fileName .. " has fewer than " .. lineNum .. " lines.") end print(fileLine(7, "test.txt"))
Preserve the algorithm and functionality while converting the code from PHP to Lua.
<?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...
function fileLine (lineNum, fileName) local count = 0 for line in io.lines(fileName) do count = count + 1 if count == lineNum then return line end end error(fileName .. " has fewer than " .. lineNum .. " lines.") end print(fileLine(7, "test.txt"))
Transform the following PHP implementation into Lua, maintaining the same output and logic.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
function encodeChar(chr) return string.format("%%%X",string.byte(chr)) end function encodeString(str) local output, t = string.gsub(str,"[^%w]",encodeChar) return output end print(encodeString("http://foo bar/"))
Change the programming language of this snippet from PHP to Lua without modifying what it does.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
function encodeChar(chr) return string.format("%%%X",string.byte(chr)) end function encodeString(str) local output, t = string.gsub(str,"[^%w]",encodeChar) return output end print(encodeString("http://foo bar/"))
Change the following PHP code into Lua without altering its purpose.
<?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 = ...
function f (x) return math.abs(x)^0.5 + 5*x^3 end function reverse (t) local rev = {} for i, v in ipairs(t) do rev[#t - (i-1)] = v end return rev end local sequence, result = {} print("Enter 11 numbers...") for n = 1, 11 do io.write(n .. ": ") sequence[n] = io.read() end for _, x in ipairs(reverse...
Convert this PHP snippet to Lua and keep its semantics consistent.
$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...
function reverse() local ch = io.read(1) if ch:find("%w") then local rc = reverse() io.write(ch) return rc end return ch end function forward() ch = io.read(1) io.write(ch) if ch == "." then return false end if not ch:find("%w") then ch = reverse() if ch then io.write(ch) end if...
Write the same algorithm in Lua as shown in this PHP implementation.
<?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;...
function Is_self_describing( n ) local s = tostring( n ) local t = {} for i = 0, 9 do t[i] = 0 end for i = 1, s:len() do local idx = tonumber( s:sub(i,i) ) t[idx] = t[idx] + 1 end for i = 1, s:len() do if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end end ret...
Write a version of this PHP function in Lua with identical behavior.
<?php foreach(file("unixdict.txt") as $w) echo (strstr($w, "the") && strlen(trim($w)) > 11) ? $w : "";
for word in io.open("unixdict.txt", "r"):lines() do if #word > 11 and word:find("the") then print(word) end end
Convert the following code from PHP to Lua, ensuring the logic remains intact.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
print([[ This is a long paragraph of text it is the simplest while using it with lua, however it will have the same line breaks and spacing as you set in this block. ]]) print([=[by using equals signs, ]] may be embedded.]=]) local msg = [[this is a message that spans multiple lines and will have the next lines ...
Can you help me rewrite this code in Lua instead of PHP, keeping it the same logically?
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
print([[ This is a long paragraph of text it is the simplest while using it with lua, however it will have the same line breaks and spacing as you set in this block. ]]) print([=[by using equals signs, ]] may be embedded.]=]) local msg = [[this is a message that spans multiple lines and will have the next lines ...
Transform the following PHP implementation into Lua, maintaining the same output and logic.
<?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...
local unpack = unpack or table.unpack game = { cell = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, best = 0, draw = function(self) local t = self.cell print("+ for r=0,12,4 do print(string.format("|%4d|%4d|%4d|%4d|\n+ end end, incr = function(self) local t,open = self.cell,{} for i=1,16 ...
Produce a language-to-language conversion: from PHP to Lua, same semantics.
while(1) echo "SPAM\n";
while true do print("SPAM") end repeat print("SPAM") until false
Ensure the translated Lua code behaves exactly like the original PHP snippet.
function multiply( $a, $b ) { return $a * $b; }
function multiply( a, b ) return a * b end
Translate this program into Lua but keep the logic exactly as in PHP.
function sattoloCycle($items) { for ($i = 0; $i < count($items); $i++) { $j = floor((mt_rand() / mt_getrandmax()) * $i); $tmp = $items[$i]; $items[$i] = $items[$j]; $items[$j] = $tmp; } return $items; }
function sattolo (items) local j for i = #items, 2, -1 do j = math.random(i - 1) items[i], items[j] = items[j], items[i] end end math.randomseed(os.time()) local testCases = { {}, {10}, {10, 20}, {10, 20, 30}, {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22} } for _, arr...
Write a version of this PHP function in Lua with identical behavior.
function sattoloCycle($items) { for ($i = 0; $i < count($items); $i++) { $j = floor((mt_rand() / mt_getrandmax()) * $i); $tmp = $items[$i]; $items[$i] = $items[$j]; $items[$j] = $tmp; } return $items; }
function sattolo (items) local j for i = #items, 2, -1 do j = math.random(i - 1) items[i], items[j] = items[j], items[i] end end math.randomseed(os.time()) local testCases = { {}, {10}, {10, 20}, {10, 20, 30}, {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22} } for _, arr...
Write the same algorithm in Lua as shown in this PHP implementation.
<?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 ) "); ?>
local sql = require("ljsqlite3") local conn = sql.open("address.sqlite") conn:exec[[ CREATE TABLE IF NOT EXISTS address( id INTEGER PRIMARY KEY AUTOINCREMENT, street TEXT NOT NULL, city TEXT NOT NULL, state TEXT NOT NULL, zip TEXT NOT NULL) ]] conn:close()
Generate a Lua translation of this PHP snippet without changing its computational steps.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed...
local a = {[0]=0} local used = {[0]=true} local used1000 = {[0]=true} local foundDup = false local n = 1 while n<=15 or not foundDup or #used1000<1001 do local nxt = a[n - 1] - n if nxt<1 or used[nxt] ~= nil then nxt = nxt + 2 * n end local alreadyUsed = used[nxt] ~= nil table.insert(a, nxt...
Maintain the same structure and functionality when rewriting this code in Lua.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed...
local a = {[0]=0} local used = {[0]=true} local used1000 = {[0]=true} local foundDup = false local n = 1 while n<=15 or not foundDup or #used1000<1001 do local nxt = a[n - 1] - n if nxt<1 or used[nxt] ~= nil then nxt = nxt + 2 * n end local alreadyUsed = used[nxt] ~= nil table.insert(a, nxt...
Convert the following code from PHP to Lua, ensuring the logic remains intact.
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "...
Y = function (f) return function(...) return (function(x) return x(x) end)(function(x) return f(function(y) return x(x)(y) end) end)(...) end end
Translate the given PHP code snippet into Lua without altering its behavior.
<?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) ...
function show (msg, t) io.write(msg .. ":\t") for _, v in pairs(t) do io.write(v .. " ") end print() end function randList (length, lo, hi) local t = {} for i = 1, length do table.insert(t, math.random(lo, hi)) end return t end function tally (list) local tal = {} for k, v in pairs(...
Translate this program into Lua but keep the logic exactly as in PHP.
$accumulator = 0; echo 'HQ9+: '; $program = trim(fgets(STDIN)); foreach (str_split($program) as $chr) { switch ($chr) { case 'H': case 'h': printHelloWorld(); break; case 'Q': case 'q': printSource($program); break; case '9': ...
function runCode( code ) local acc, lc = 0 for i = 1, #code do lc = code:sub( i, i ):upper() if lc == "Q" then print( lc ) elseif lc == "H" then print( "Hello, World!" ) elseif lc == "+" then acc = acc + 1 elseif lc == "9" then for j = 99, 1, -1 do ...
Convert this PHP snippet to Lua and keep its semantics consistent.
$accumulator = 0; echo 'HQ9+: '; $program = trim(fgets(STDIN)); foreach (str_split($program) as $chr) { switch ($chr) { case 'H': case 'h': printHelloWorld(); break; case 'Q': case 'q': printSource($program); break; case '9': ...
function runCode( code ) local acc, lc = 0 for i = 1, #code do lc = code:sub( i, i ):upper() if lc == "Q" then print( lc ) elseif lc == "H" then print( "Hello, World!" ) elseif lc == "+" then acc = acc + 1 elseif lc == "9" then for j = 99, 1, -1 do ...
Port the provided PHP code into Lua while preserving the original functionality.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; ...
local funs = { ['>'] = 'ptr = ptr + 1; ', ['<'] = 'ptr = ptr - 1; ', ['+'] = 'mem[ptr] = mem[ptr] + 1; ', ['-'] = 'mem[ptr] = mem[ptr] - 1; ', ['['] = 'while mem[ptr] ~= 0 do ', [']'] = 'end; ', ['.'] = 'io.write(string.char(mem[ptr])); ', [','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ', } local prog = [[ local ...
Convert this PHP snippet to Lua and keep its semantics consistent.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; ...
local funs = { ['>'] = 'ptr = ptr + 1; ', ['<'] = 'ptr = ptr - 1; ', ['+'] = 'mem[ptr] = mem[ptr] + 1; ', ['-'] = 'mem[ptr] = mem[ptr] - 1; ', ['['] = 'while mem[ptr] ~= 0 do ', [']'] = 'end; ', ['.'] = 'io.write(string.char(mem[ptr])); ', [','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ', } local prog = [[ local ...
Write a version of this PHP function in Lua with identical behavior.
class Card { protected static $suits = array( 'β™ ', 'β™₯', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __c...
suits = {"Clubs", "Diamonds", "Hearts", "Spades"} faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"} stack = setmetatable({ __unm = function(z) local ret = {} for i = #z, 1, -1 do ret[#ret + 1] = table.remove(z,math.random(i)) end return setmetatable(ret, stack) end, __add = function(z, z2) for ...
Rewrite this program in Lua while keeping its functionality equivalent to the PHP version.
<?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...
function _deepcopy(o, tables) if type(o) ~= 'table' then return o end if tables[o] ~= nil then return tables[o] end local new_o = {} tables[o] = new_o for k, v in next, o, nil do local new_k = _deepcopy(k, tables) local new_v = _deepcopy(v, tables) new_o[new_k] = new_v end ...
Can you help me rewrite this code in Lua instead of PHP, keeping it the same logically?
<?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...
function _deepcopy(o, tables) if type(o) ~= 'table' then return o end if tables[o] ~= nil then return tables[o] end local new_o = {} tables[o] = new_o for k, v in next, o, nil do local new_k = _deepcopy(k, tables) local new_v = _deepcopy(v, tables) new_o[new_k] = new_v end ...
Generate a Lua translation of this PHP snippet without changing its computational steps.
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) ...
function permute (list) local function perm (list, n) if n == 0 then coroutine.yield(list) end for i = 1, n do list[i], list[n] = list[n], list[i] perm(list, n - 1) list[i], list[n] = list[n], list[i] end end return coroutine.wrap(function() perm(list, #list) end) end function inO...
Rewrite the snippet below in Lua so it works the same as the original PHP code.
<?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); } ?>
#!/usr/bin/env lua function meaningoflife() return 42 end function main(arg) print("Main: The meaning of life is " .. meaningoflife()) end if type(package.loaded[(...)]) ~= "userdata" then main(arg) else module(..., package.seeall) end
Write a version of this PHP function in Lua with identical behavior.
<?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); } ?>
#!/usr/bin/env lua function meaningoflife() return 42 end function main(arg) print("Main: The meaning of life is " .. meaningoflife()) end if type(package.loaded[(...)]) ~= "userdata" then main(arg) else module(..., package.seeall) end
Change the following PHP code into Lua without altering its purpose.
<?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 ...
function isLeapYear (y) return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0 end function dayOfWeek (y, m, d) local t = os.time({year = y, month = m, day = d}) return os.date("%A", t) end function lastWeekdays (wday, year) local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} if...
Write the same code in Lua as shown below 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 ...
function isLeapYear (y) return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0 end function dayOfWeek (y, m, d) local t = os.time({year = y, month = m, day = d}) return os.date("%A", t) end function lastWeekdays (wday, year) local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} if...
Port the following code from PHP to Lua with equivalent syntax and logic.
<?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) $...
function buildLIS(seq) local piles = { { {table.remove(seq, 1), nil} } } while #seq>0 do local x=table.remove(seq, 1) for j=1,#piles do if piles[j][#piles[j]][1]>x then table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])}) break elseif ...
Generate a Lua translation of this PHP snippet without changing its computational steps.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
_G[io.read()] = 5
Change the programming language of this snippet from PHP to Lua without modifying what it does.
<?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". ?>
code = loadstring"return x^2" val1 = setfenv(code, {x = io.read() + 0})() val2 = setfenv(code, {x = io.read() + 0})() print(val2 - val1)
Rewrite this program in Lua while keeping its functionality equivalent to the PHP version.
<?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". ?>
code = loadstring"return x^2" val1 = setfenv(code, {x = io.read() + 0})() val2 = setfenv(code, {x = io.read() + 0})() print(val2 - val1)
Ensure the translated Lua code behaves exactly like the original PHP snippet.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
f = loadstring(s) one = loadstring"return 1" two = loadstring"return ..."
Write the same code in Lua as shown below in PHP.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
f = loadstring(s) one = loadstring"return 1" two = loadstring"return ..."
Change the programming language of this snippet from PHP to Lua without modifying what it does.
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 = []; ...
local function wrapEachItem(items, prefix, suffix) local itemsWrapped = {} for i, item in ipairs(items) do itemsWrapped[i] = prefix .. item .. suffix end return itemsWrapped end local function getAllItemCombinationsConcatenated(aItems, bItems) local combinations = {} for _, a in ipairs(aItems) do for _, b...
Keep all operations the same but rewrite the snippet in Lua.
<?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...
require 'lxp' data = [[<inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitatio...
Please provide an equivalent version of this PHP code in Lua.
$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", ...
local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" } local dicE, dicD, s1, s2 = {}, {}, 0, 0 function dec( txt ) local i, numb, s, t, c = 1, false while( i < #txt ) do c = txt:sub( i, i ) if not numb then if tonumber( c ) == s1 then i = i + 1; s = string.format( ...
Maintain the same structure and functionality when rewriting this code in Lua.
<?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...
local object={print=print} setmetatable(object,{__index=function(t,k)return function() print("You called the method",k)end end}) object.print("Hi") object.hello()
Produce a functionally identical Lua code for the snippet given in PHP.
<?php function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return fal...
function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end local i, p = 0 repeat i = i + 1 p = 2 ^ i - 1 if isPrime(p) then print("2 ^ " .. i .. "...
Ensure the translated Lua code behaves exactly like the original PHP snippet.
<?php function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return fal...
function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end local i, p = 0 repeat i = i + 1 p = 2 ^ i - 1 if isPrime(p) then print("2 ^ " .. i .. "...
Rewrite the snippet below in Lua 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"), ...
local function recA(age, name) return { Age=age, Name=name } end local tabA = { recA(27,"Jonah"), recA(18,"Alan"), recA(28,"Glory"), recA(18,"Popeye"), recA(28,"Alan") } local function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end local tabB = { recB("Jonah","Whales"), recB("Jonah","Spid...
Change the following PHP code into Lua without altering its purpose.
<?php $zero = function($f) { return function ($x) { return $x; }; }; $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; }; $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$...
function churchZero() return function(x) return x end end function churchSucc(c) return function(f) return function(x) return f(c(f)(x)) end end end function churchAdd(c, d) return function(f) return function(x) return c(f)(d(f)(x)) end end end function churchMul(c, d...
Convert this PHP block to Lua, preserving its control flow and logic.
<?php $zero = function($f) { return function ($x) { return $x; }; }; $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; }; $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$...
function churchZero() return function(x) return x end end function churchSucc(c) return function(f) return function(x) return f(c(f)(x)) end end end function churchAdd(c, d) return function(f) return function(x) return c(f)(d(f)(x)) end end end function churchMul(c, d...
Translate this program into Lua but keep the logic exactly as in PHP.
<? 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; } ?>
function helloWorld() print "Hello World" end function printFunctions(t) local s={} local n=0 for k in pairs(t) do n=n+1 s[n]=k end table.sort(s) for k,v in ipairs(s) do f = t[v] if type(f) == "function" then print(v) end end end printFuncti...
Please provide an equivalent version of this PHP code in Lua.
<?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"; ?>
local example = { } function example:foo (x) return 42 + x end local name = "foo" example[name](example, 5)
Convert the following code from PHP to Lua, ensuring the logic remains intact.
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
a = 1 b = 2.0 c = "hello world" function listProperties(t) if type(t) == "table" then for k,v in pairs(t) do if type(v) ~= "function" then print(string.format("%7s: %s", type(v), k)) end end end end print("Global properties") listProperties(_G) print("Pa...
Change the following PHP code into Lua without altering its purpose.
<?php function markovChainTextGenerator($text, $keySize, $maxWords) { $token = array(); $position = 0; $maxPosition = strlen($text); while ($position < $maxPosition) { if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) { $token[] = $matches[1]; $positio...
local function pick(t) local i = math.ceil(math.random() * #t) return t[i] end local n_prevs = tonumber(arg[1]) or 2 local n_words = tonumber(arg[2]) or 8 local dict, wordset = {}, {} local prevs, pidx = {}, 1 local function add(word) local prev = '' local i, len = pidx, #prevs for _ = 1, len do i ...
Produce a functionally identical Julia code for the snippet given in C#.
using static System.Console; using static System.Threading.Thread; using System; public static class PenneysGame { const int pause = 500; const int N = 3; static Random rng = new Random(); static int Toss() => rng.Next(2); static string AsString(this int sequence) { string s = ""; ...
const SLEN = 3 autobet() = randbool(SLEN) function autobet(ob::BitArray{1}) rlen = length(ob) 2 < rlen || return ~ob 3 < rlen || return [~ob[2], ob[1:2]] opt = falses(rlen) opt[1] = true opt[end-1:end] = true ob != opt || return ~opt return opt end autobet(ob::Array{Bool,1}) = autobet(c...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; using System.Linq; using System.Text; public static class Nonoblock { public static void Main() { Positions(5, 2,1); Positions(5); Positions(10, 8); Positions(15, 2,3,2,3); Positions(5, 2,3); } public static void Positions(int cells, params int[] block...
minsized(arr) = join(map(x->" minlen(arr) = sum(arr) + length(arr) - 1 function sequences(blockseq, numblanks) if isempty(blockseq) return ["." ^ numblanks] elseif minlen(blockseq) == numblanks return minsized(blockseq) else result = Vector{String}() allbuthead = blocks...
Can you help me rewrite this code in Julia instead of C#, keeping it the same logically?
using System; using System.Linq; using System.Text; public static class Nonoblock { public static void Main() { Positions(5, 2,1); Positions(5); Positions(10, 8); Positions(15, 2,3,2,3); Positions(5, 2,3); } public static void Positions(int cells, params int[] block...
minsized(arr) = join(map(x->" minlen(arr) = sum(arr) + length(arr) - 1 function sequences(blockseq, numblanks) if isempty(blockseq) return ["." ^ numblanks] elseif minlen(blockseq) == numblanks return minsized(blockseq) else result = Vector{String}() allbuthead = blocks...
Ensure the translated Julia code behaves exactly like the original C# snippet.
using System; namespace EbanNumbers { struct Interval { public int start, end; public bool print; public Interval(int start, int end, bool print) { this.start = start; this.end = end; this.print = print; } } class Program { stati...
function iseban(n::Integer) b, r = divrem(n, oftype(n, 10 ^ 9)) m, r = divrem(r, oftype(n, 10 ^ 6)) t, r = divrem(r, oftype(n, 10 ^ 3)) m, t, r = (30 <= x <= 66 ? x % 10 : x for x in (m, t, r)) return all(in((0, 2, 4, 6)), (b, m, t, r)) end println("eban numbers up to and including 1000:") println(...
Translate the given C# code snippet into Julia without altering its behavior.
using System; namespace EbanNumbers { struct Interval { public int start, end; public bool print; public Interval(int start, int end, bool print) { this.start = start; this.end = end; this.print = print; } } class Program { stati...
function iseban(n::Integer) b, r = divrem(n, oftype(n, 10 ^ 9)) m, r = divrem(r, oftype(n, 10 ^ 6)) t, r = divrem(r, oftype(n, 10 ^ 3)) m, t, r = (30 <= x <= 66 ? x % 10 : x for x in (m, t, r)) return all(in((0, 2, 4, 6)), (b, m, t, r)) end println("eban numbers up to and including 1000:") println(...
Convert the following code from C# to Julia, ensuring the logic remains intact.
class Test { static bool 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); } static vo...
function validnutsforsailors(sailors, finalpile) for i in sailors:-1:1 if finalpile % sailors != 1 return false end finalpile -= Int(floor(finalpile/sailors) + 1) end (finalpile != 0) && (finalpile % sailors == 0) end function runsim() println("Sailors Starting P...
Port the following code from C# to Julia with equivalent syntax and logic.
class Test { static bool 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); } static vo...
function validnutsforsailors(sailors, finalpile) for i in sailors:-1:1 if finalpile % sailors != 1 return false end finalpile -= Int(floor(finalpile/sailors) + 1) end (finalpile != 0) && (finalpile % sailors == 0) end function runsim() println("Sailors Starting P...
Rewrite this program in Julia while keeping its functionality equivalent to the C# version.
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading; namespace Polyspiral { public partial class Form1 : Form { private double inc; public Form1() { Width = Height = 640; StartPosition = ...
using Gtk, Graphics, Colors const can = @GtkCanvas() const win = GtkWindow(can, "Polyspiral", 360, 360) const drawiters = 72 const colorseq = [colorant"blue", colorant"red", colorant"green", colorant"black", colorant"gold"] const angleiters = [0, 0, 0] const angles = [75, 100, 135, 160] Base.length(v::Vec2) = sqrt(v...
Preserve the algorithm and functionality while converting the code from C# to Julia.
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading; namespace Polyspiral { public partial class Form1 : Form { private double inc; public Form1() { Width = Height = 640; StartPosition = ...
using Gtk, Graphics, Colors const can = @GtkCanvas() const win = GtkWindow(can, "Polyspiral", 360, 360) const drawiters = 72 const colorseq = [colorant"blue", colorant"red", colorant"green", colorant"black", colorant"gold"] const angleiters = [0, 0, 0] const angles = [75, 100, 135, 160] Base.length(v::Vec2) = sqrt(v...
Keep all operations the same but rewrite the snippet in Julia.
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; public static class MergeAndAggregateDatasets { public static void Main() { string patientsCsv = @" PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005...
using CSV, DataFrames, Statistics str_patients = IOBuffer("""PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz """) df_patients = CSV.read(str_patients, DataFrame) str_visits = IOBuffer("""PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,202...
Write the same code in Julia as shown below in C#.
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
using LDAPClient conn = LDAPClient.LDAPConnection("ldap://localhost:10389") LDAPClient.simple_bind(conn, "user", "password") LDAPClient.unbind(conn)