Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided PHP code into D while preserving the original functionality.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
import std.stdio, std.uri; void main() { writeln(encodeComponent("http: }
Keep all operations the same but rewrite the snippet in D.
<?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 = ...
import std.stdio, std.math, std.conv, std.algorithm, std.array; double f(in double x) pure nothrow { return x.abs.sqrt + 5 * x ^^ 3; } void main() { double[] data; while (true) { "Please enter eleven numbers on a line: ".write; data = readln.split.map!(to!double).array; if (data.l...
Port the following code from PHP to D with equivalent syntax and logic.
$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...
bool doChar(in bool odd, in void delegate() nothrow f=null) nothrow { import core.stdc.stdio, std.ascii; immutable int c = getchar; if (!odd) c.putchar; if (c.isAlpha) return doChar(odd, { c.putchar; if (f) f(); }); if (odd) { if (f) f(); c.putchar; } return ...
Produce a functionally identical D code for the snippet given in PHP.
<?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;...
import std.stdio, std.algorithm, std.range, std.conv, std.string; bool isSelfDescribing(in long n) pure nothrow @safe { auto nu = n.text.representation.map!q{ a - '0' }; return nu.length.iota.map!(a => nu.count(a)).equal(nu); } void main() { 4_000_000.iota.filter!isSelfDescribing.writeln; }
Preserve the algorithm and functionality while converting the code from PHP to D.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
import std.stdio, std.string; void main() { q"[a string that you "don't" have to escape]" .writeln; q"EOS This is a multi-line heredoc string EOS".outdent.writeln; }
Rewrite this program in D while keeping its functionality equivalent to the PHP version.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
import std.stdio, std.string; void main() { q"[a string that you "don't" have to escape]" .writeln; q"EOS This is a multi-line heredoc string EOS".outdent.writeln; }
Write the same code in D as shown below in PHP.
<?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...
import std.stdio, std.string, std.random; import core.stdc.stdlib: exit; struct G2048 { void gameLoop() { addTile; while (true) { if (moved) addTile; drawBoard; if (done) break; waitKey; } writeln(win ? ...
Ensure the translated D code behaves exactly like the original PHP snippet.
while(1) echo "SPAM\n";
import std.stdio; void main() { while (true) writeln("SPAM"); }
Translate this program into D but keep the logic exactly as in PHP.
function multiply( $a, $b ) { return $a * $b; }
int multiply1(int a, int b) { return a * b; } enum result = multiply1(2, 3); int[multiply1(2, 4)] array; T multiply2(T)(T a, T b) { return a * b; } enum multiply3(int a, int b) = a * b; pragma(msg, multiply3!(2, 3)); void main() { import std.stdio; writeln("2 * 3 = ", result); }
Transform the following PHP implementation into D, maintaining the same output and logic.
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; }
import std.stdio; void main() { auto items = [0,1,2,3,4,5]; sattoloCycle(items); items.writeln; } void sattoloCycle(R)(R items) { import std.algorithm : swapAt; import std.random : uniform; for (int i=items.length; i-- > 1;) { int j = uniform(0, i); items.swapAt(i, j); } ...
Produce a language-to-language conversion: from PHP to D, same semantics.
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; }
import std.stdio; void main() { auto items = [0,1,2,3,4,5]; sattoloCycle(items); items.writeln; } void sattoloCycle(R)(R items) { import std.algorithm : swapAt; import std.random : uniform; for (int i=items.length; i-- > 1;) { int j = uniform(0, i); items.swapAt(i, j); } ...
Rewrite this program in D while keeping its functionality equivalent to the PHP version.
<?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...
import std.stdio; void main() { int[] a; bool[int] used; bool[int] used1000; bool foundDup; a ~= 0; used[0] = true; used1000[0] = true; int n = 1; while (n <= 15 || !foundDup || used1000.length < 1001) { int next = a[n - 1] - n; if (next < 1 || (next in used) !is n...
Change the following PHP code into D without altering its purpose.
<?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...
import std.stdio; void main() { int[] a; bool[int] used; bool[int] used1000; bool foundDup; a ~= 0; used[0] = true; used1000[0] = true; int n = 1; while (n <= 15 || !foundDup || used1000.length < 1001) { int next = a[n - 1] - n; if (next < 1 || (next in used) !is n...
Preserve the algorithm and functionality while converting the code from PHP to D.
<?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), "...
import std.stdio, std.traits, std.algorithm, std.range; auto Y(S, T...)(S delegate(T) delegate(S delegate(T)) f) { static struct F { S delegate(T) delegate(F) f; alias f this; } return (x => x(x))(F(x => f((T v) => x(x)(v)))); } void main() { auto factorial = Y((int delegate(int) self...
Keep all operations the same but rewrite the snippet in D.
<?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) ...
import std.stdio, std.algorithm, std.range, std.array, std.functional; alias repeat0 = curry!(repeat, 0); auto columns(R)(R m) pure @safe { return m .map!walkLength .reduce!max .iota .map!(i => m.filter!(s => s.length > i).walkLength.repeat0); } auto beadSort(in uin...
Rewrite the snippet below in D so it works the same as the original PHP code.
$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': ...
import std.stdio, std.string; void main(in string[] args) { if (args.length != 2 || args[1].length != args[1].countchars("hHqQ9+")) { writeln("Not valid HQ9+ code."); return; } ulong accumulator; foreach (immutable c; args[1]) { final switch(c) { case 'Q', '...
Keep all operations the same but rewrite the snippet in D.
$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': ...
import std.stdio, std.string; void main(in string[] args) { if (args.length != 2 || args[1].length != args[1].countchars("hHqQ9+")) { writeln("Not valid HQ9+ code."); return; } ulong accumulator; foreach (immutable c; args[1]) { final switch(c) { case 'Q', '...
Write the same code in D as shown below in PHP.
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...
import std.stdio, std.typecons, std.algorithm, std.traits, std.array, std.range, std.random; enum Pip {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace} enum Suit {Diamonds, Spades, Hearts, Clubs} alias Card = Tuple!(Pip, Suit); auto newDeck() pure nothrow @safe { retu...
Please provide an equivalent version of this PHP code in D.
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) ...
import std.stdio, std.algorithm, permutations2; void permutationSort(T)(T[] items) pure nothrow @safe @nogc { foreach (const perm; items.permutations!false) if (perm.isSorted) break; } void main() { auto data = [2, 7, 4, 3, 5, 1, 0, 9, 8, 6, -1]; data.permutationSort; data.writeln;...
Keep all operations the same but rewrite the snippet in D.
<?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 rdmd -version=scriptedmain module scriptedmain; import std.stdio; int meaningOfLife() { return 42; } version (scriptedmain) { void main(string[] args) { writeln("Main: The meaning of life is ", meaningOfLife()); } }
Keep all operations the same but rewrite the snippet in D.
<?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 rdmd -version=scriptedmain module scriptedmain; import std.stdio; int meaningOfLife() { return 42; } version (scriptedmain) { void main(string[] args) { writeln("Main: The meaning of life is ", meaningOfLife()); } }
Rewrite the snippet below in D so it works the same as the original 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 ...
void lastSundays(in uint year) { import std.stdio, std.datetime; foreach (immutable month; 1 .. 13) { auto date = Date(year, month, 1); date.day(date.daysInMonth); date.roll!"days"(-(date.dayOfWeek + 7) % 7); date.writeln; } } void main() { lastSundays(2013); }
Rewrite the snippet below in D so it works the same as the original 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 ...
void lastSundays(in uint year) { import std.stdio, std.datetime; foreach (immutable month; 1 .. 13) { auto date = Date(year, month, 1); date.day(date.daysInMonth); date.roll!"days"(-(date.dayOfWeek + 7) % 7); date.writeln; } } void main() { lastSundays(2013); }
Rewrite this program in D while keeping its functionality equivalent to the PHP version.
<?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) $...
import std.stdio, std.algorithm, power_set2; T[] lis(T)(T[] items) pure nothrow { return items .powerSet .filter!isSorted .minPos!q{ a.length > b.length } .front; } void main() { [3, 2, 6, 4, 5, 1].lis.writeln; [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11...
Convert this PHP block to D, preserving its control flow 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 = []; ...
import std.stdio, std.typecons, std.array, std.range, std.algorithm, std.string; Nullable!(Tuple!(string[], string)) getGroup(string s, in uint depth) pure nothrow @safe { string[] sout; auto comma = false; while (!s.empty) { const r = getItems(s, depth); const g = r[0]; s...
Transform the following PHP implementation into D, maintaining the same output and logic.
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
import openldap; import std.stdio; void main() { auto ldap = LDAP("ldap: auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test")); int b = ldap.bind_s(r[0].dn, "password"); scope(exit) ldap.unbind; if (b) { writeln("error on binding"); return; } ... }
Port the following code from PHP to D 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();...
import std.stdio, std.container; DList!T strandSort(T)(DList!T list) { static DList!T merge(DList!T left, DList!T right) { DList!T result; while (!left.empty && !right.empty) { if (left.front <= right.front) { result.insertBack(left.front); left.removeFro...
Port the provided PHP code into D while preserving the original functionality.
<?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...
import kxml.xml; char[]xmlinput = "<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\...
Translate the given PHP code snippet into D 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'...
import std.stdio, std.file, std.string, std.regex, std.path, std.typecons; final class Config { enum EntryType { empty, enabled, disabled, comment, ignore } static protected struct Entry { EntryType type; string name, value; } protected Entry[] entries; protected string path...
Change the programming language of this snippet from PHP to D without modifying what it does.
$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", ...
import std.stdio, std.algorithm, std.string, std.array; immutable T = ["79|0|1|2|3|4|5|6|7|8|9", "|H|O|L||M|E|S||R|T", "3|A|B|C|D|F|G|I|J|K|N", "7|P|Q|U|V|W|X|Y|Z|.|/"] .map!(r => r.split("|")).array; enum straddle = (in string s) pure => toUpper(s) .split("") .cartesianProdu...
Produce a functionally identical D 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...
import std.stdio; struct Catcher { void foo() { writeln("This is foo"); } void bar() { writeln("This is bar"); } void opDispatch(string name, ArgsTypes...)(ArgsTypes args) { writef("Tried to handle unknown method '%s'", name); if (ArgsTypes.length) { write(", with arguments: "...
Write a version of this PHP function in D with identical behavior.
<?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...
import std.bigint; import std.stdio; bool isPrime(BigInt bi) { if (bi < 2) return false; if (bi % 2 == 0) return bi == 2; if (bi % 3 == 0) return bi == 3; auto test = BigInt(5); while (test * test < bi) { if (bi % test == 0) return false; test += 2; if (bi % test == 0) ...
Port the following code from PHP to D with equivalent syntax and logic.
<?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...
import std.bigint; import std.stdio; bool isPrime(BigInt bi) { if (bi < 2) return false; if (bi % 2 == 0) return bi == 2; if (bi % 3 == 0) return bi == 3; auto test = BigInt(5); while (test * test < bi) { if (bi % test == 0) return false; test += 2; if (bi % test == 0) ...
Keep all operations the same but rewrite the snippet in D.
<?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"), ...
import std.stdio, std.typecons; auto hashJoin(size_t index1, size_t index2, T1, T2) (in T1[] table1, in T2[] table2) pure @safe if (is(typeof(T1.init[index1]) == typeof(T2.init[index2]))) { T1[][typeof(T1.init[index1])] h; foreach (const s; table1) h[s[index1]] ~= s; Tuple!...
Ensure the translated D code behaves exactly like the original PHP snippet.
<?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...
#include <stdio.h> #include <stdlib.h> int main(){ int temp; int numbers=3; int a[numbers+1], upto = 4, temp2; for( temp2 = 1 ; temp2 <= numbers; temp2++){ a[temp2]=1; } a[numbers]=0; temp=numbers; while(1){ if(a[temp]==upto){ temp--; if(temp==0) break; } else{ a[temp]++; while(temp<nu...
Change the following PHP code into D without altering its purpose.
<?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...
#include <stdio.h> #include <stdlib.h> int main(){ int temp; int numbers=3; int a[numbers+1], upto = 4, temp2; for( temp2 = 1 ; temp2 <= numbers; temp2++){ a[temp2]=1; } a[numbers]=0; temp=numbers; while(1){ if(a[temp]==upto){ temp--; if(temp==0) break; } else{ a[temp]++; while(temp<nu...
Write the same code in D as shown below 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; } ?>
struct S { bool b; void foo() {} private void bar() {} } class C { bool b; void foo() {} private void bar() {} } void printMethods(T)() if (is(T == class) || is(T == struct)) { import std.stdio; import std.traits; writeln("Methods of ", T.stringof, ":"); foreach (m; __traits...
Write a version of this PHP function in D with identical behavior.
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...
import std.algorithm; import std.exception : enforce; import std.math; import std.stdio; void main() { creal[] pointList = [ 0.0 + 0.0i, 1.0 + 0.1i, 2.0 + -0.1i, 3.0 + 5.0i, 4.0 + 6.0i, 5.0 + 7.0i, 6.0 + 8.1i, 7.0 + 9.0i, 8.0 + 9.0i, ...
Generate an equivalent D version of this PHP code.
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...
import std.algorithm; import std.exception : enforce; import std.math; import std.stdio; void main() { creal[] pointList = [ 0.0 + 0.0i, 1.0 + 0.1i, 2.0 + -0.1i, 3.0 + 5.0i, 4.0 + 6.0i, 5.0 + 7.0i, 6.0 + 8.1i, 7.0 + 9.0i, 8.0 + 9.0i, ...
Port the following code from PHP to D with equivalent syntax and logic.
<?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...
import openldap; import std.stdio; void main() { auto ldap = LDAP("ldap: auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test")); writeln("Found dn: %s", r[0].dn); foreach(k, v; r[0].entry) writeln("%s = %s", k, v); int b = ldap.bind_s(r[0].dn, "password"...
Please provide an equivalent version of this PHP code in D.
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
import std.stdio; struct S { bool b; void foo() {} private void bar() {} } class C { bool b; void foo() {} private void bar() {} } void printProperties(T)() if (is(T == class) || is(T == struct)) { import std.stdio; import std.traits; writeln("Properties of ", T.stringof, ':');...
Ensure the translated D code behaves exactly like the original PHP snippet.
<?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...
import std.file; import std.random; import std.range; import std.stdio; import std.string; string markov(string filePath, int keySize, int outputSize) { if (keySize < 1) throw new Exception("Key size can't be less than 1"); auto words = filePath.readText().chomp.split; if (outputSize < keySize || words.len...
Convert this PHP block to D, preserving its control flow and logic.
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...
import core.stdc.stdio, std.math, std.typecons, std.string, std.conv, std.algorithm, std.ascii, std.array, bitmap, grayscale_image; enum maxBrightness = 255; alias Pixel = short; alias IntT = typeof(size_t.init.signed); void convolution(bool normalize)(in Pixel[] inp, Pixel[] outp, ...
Ensure the translated D code behaves exactly like the original PHP snippet.
function ownCalcPass($password, $nonce) { $msr = 0x7FFFFFFF; $m_1 = (int)0xFFFFFFFF; $m_8 = (int)0xFFFFFFF8; $m_16 = (int)0xFFFFFFF0; $m_128 = (int)0xFFFFFF80; $m_16777216 = (int)0xFF000000; $flag = True; $num1 = 0; $num2 = 0; foreach (str_split($nonce) as $c) { $num1 = ...
import std.stdio, std.string, std.conv, std.ascii, std.algorithm; ulong ownCalcPass(in ulong password, in string nonce) pure nothrow @safe @nogc in { assert(nonce.representation.all!isDigit); } body { enum ulong m_1 = 0x_FFFF_FFFF_UL; enum ulong m_8 = 0x_FFFF_FFF8_UL; enum ulong m_16 ...
Change the programming language of this snippet from C# to COBOL without modifying what it does.
readonly DateTime now = DateTime.Now;
ENVIRONMENT DIVISION. CONFIGURATION SECTION. SPECIAL-NAMES. SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9.
Produce a language-to-language conversion: from C# to COBOL, same semantics.
int i = 5; int* p = &i;
data division. working-storage section. 01 ptr usage pointer. 01 var pic x(64). procedure division. set ptr to address of var.
Transform the following C# implementation into COBOL, maintaining the same output and logic.
while (true) { Console.WriteLine("SPAM"); }
IDENTIFICATION DIVISION. PROGRAM-ID. Spam. PROCEDURE DIVISION. PERFORM UNTIL 1 <> 1 DISPLAY "SPAM" END-PERFORM GOBACK .
Write the same algorithm in COBOL as shown in this C# implementation.
static double multiply(double a, double b) { return a * b; }
IDENTIFICATION DIVISION. PROGRAM-ID. myTest. DATA DIVISION. WORKING-STORAGE SECTION. 01 x PIC 9(3) VALUE 3. 01 y PIC 9(3) VALUE 2. 01 z PIC 9(9). PROCEDURE DIVISION. CALL "myMultiply" USING BY CONTENT x, BY CONTENT y, ...
Write the same code in COBOL as shown below in C#.
static void Main(string[] args) { int bufferHeight = Console.BufferHeight; int bufferWidth = Console.BufferWidth; int windowHeight = Console.WindowHeight; int windowWidth = Console.WindowWidth; Console.Write("Buffer Height: "); Console.WriteLine(bufferHeight); Console.Write("Buffer Width: "...
IDENTIFICATION DIVISION. PROGRAM-ID. terminal-dimensions. DATA DIVISION. WORKING-STORAGE SECTION. 01 num-lines PIC 9(3). 01 num-cols PIC 9(3). SCREEN SECTION. 01 display-screen. 03 LINE 01 COL 01 PIC 9(3) FROM num-lines. 03 LINE 01 CO...
Write the same algorithm in COBOL as shown in this C# implementation.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; ...
IDENTIFICATION DIVISION. PROGRAM-ID. RECAMAN. DATA DIVISION. WORKING-STORAGE SECTION. 01 RECAMAN-SEQUENCE COMP. 02 A PIC 999 OCCURS 99 TIMES INDEXED BY I. 02 N PIC 999 VALUE 0. 01 VARIABLES COMP. 02 ADDC PIC S...
Produce a language-to-language conversion: from C# to COBOL, same semantics.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; ...
IDENTIFICATION DIVISION. PROGRAM-ID. RECAMAN. DATA DIVISION. WORKING-STORAGE SECTION. 01 RECAMAN-SEQUENCE COMP. 02 A PIC 999 OCCURS 99 TIMES INDEXED BY I. 02 N PIC 999 VALUE 0. 01 VARIABLES COMP. 02 ADDC PIC S...
Convert the following code from C# to COBOL, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.Linq; class Program { static void RunCode(string code) { int accumulator = 0; var opcodes = new Dictionary<char, Action> { {'H', () => Console.WriteLine("Hello, World!"))}, {'Q', () => Console.WriteLine...
IDENTIFICATION DIVISION. PROGRAM-ID. Exec-Hq9. DATA DIVISION. LOCAL-STORAGE SECTION. 78 Code-Length VALUE 256. 01 i PIC 999. 01 accumulator PIC 999. 01 bottles PIC 999. LINKAGE SECTION. 01 hq9-code PIC X(Code-Length). ...
Transform the following C# implementation into COBOL, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; class Program { static void RunCode(string code) { int accumulator = 0; var opcodes = new Dictionary<char, Action> { {'H', () => Console.WriteLine("Hello, World!"))}, {'Q', () => Console.WriteLine...
IDENTIFICATION DIVISION. PROGRAM-ID. Exec-Hq9. DATA DIVISION. LOCAL-STORAGE SECTION. 78 Code-Length VALUE 256. 01 i PIC 999. 01 accumulator PIC 999. 01 bottles PIC 999. LINKAGE SECTION. 01 hq9-code PIC X(Code-Length). ...
Generate an equivalent COBOL version of this C# code.
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"...
identification division. program-id. playing-cards. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 77 card usage index. 01 deck. 05 cards occurs 52 ...
Keep all operations the same but rewrite the snippet in COBOL.
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
program-id. last-sun. data division. working-storage section. 1 wk-date. 2 yr pic 9999. 2 mo pic 99 value 1. 2 da pic 99 value 1. 1 rd-date redefines wk-date pic 9(8). 1 binary. 2 int-date pic 9(8). 2 dow pic 9(4). 2 sunday pic 9(...
Keep all operations the same but rewrite the snippet in COBOL.
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
program-id. last-sun. data division. working-storage section. 1 wk-date. 2 yr pic 9999. 2 mo pic 99 value 1. 2 da pic 99 value 1. 1 rd-date redefines wk-date pic 9(8). 1 binary. 2 int-date pic 9(8). 2 dow pic 9(4). 2 sunday pic 9(...
Translate this program into COBOL but keep the logic exactly as in C#.
using System; class Program { static void Main(string[] args) { int i, d, s, t, n = 50, c = 1; var sw = new int[n]; for (i = d = s = 1; c < n; i++, s += d += 2) for (t = s; t > 0; t /= 10) if (t < n && sw[t] < 1) Console.Write("", sw[t] = ...
IDENTIFICATION DIVISION. PROGRAM-ID. SMALLEST-SQUARE-BEGINS-WITH-N. DATA DIVISION. WORKING-STORAGE SECTION. 01 N PIC 99. 01 SQUARE-NO PIC 999. 01 SQUARE PIC 9(5). 01 OUT-FMT PIC Z(4)9. PROCEDURE DIVISION. BEGIN. ...
Port the provided C# code into COBOL while preserving the original functionality.
using System; class Program { static void Main(string[] args) { int i, d, s, t, n = 50, c = 1; var sw = new int[n]; for (i = d = s = 1; c < n; i++, s += d += 2) for (t = s; t > 0; t /= 10) if (t < n && sw[t] < 1) Console.Write("", sw[t] = ...
IDENTIFICATION DIVISION. PROGRAM-ID. SMALLEST-SQUARE-BEGINS-WITH-N. DATA DIVISION. WORKING-STORAGE SECTION. 01 N PIC 99. 01 SQUARE-NO PIC 999. 01 SQUARE PIC 9(5). 01 OUT-FMT PIC Z(4)9. PROCEDURE DIVISION. BEGIN. ...
Maintain the same structure and functionality when rewriting this code in COBOL.
using System; namespace SpecialDivisors { class Program { static int Reverse(int n) { int result = 0; while (n > 0) { result = 10 * result + n % 10; n /= 10; } return result; } static void Main() { ...
IDENTIFICATION DIVISION. PROGRAM-ID. SPECIAL-DIVISORS. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 02 CANDIDATE PIC 999. 02 CAND-REV PIC 999. 02 REVERSE PIC 999. 02 REV-DIGITS REDEFIN...
Rewrite the snippet below in PowerShell so it works the same as the original C# code.
using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { int[] arr = { 0, 2, 11, 19, 90 }; const int sum = 21; var ts = TwoSum(arr, sum); Console.WriteLine(ts != null ? $"{ts[0]}, {ts[1]}" : "no result"); Console.R...
$numbers = @(0, 2, 11, 19, 90) $sum = 21 $totals = for ($i = 0; $i -lt $numbers.Count; $i++) { for ($j = $numbers.Count-1; $j -ge 0; $j--) { [PSCustomObject]@{ FirstIndex = $i SecondIndex = $j TargetSum = $numbers[$i] + $numbers[$j] } } } $totals | ...
Convert the following code from C# to PowerShell, ensuring the logic remains intact.
using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { int[] arr = { 0, 2, 11, 19, 90 }; const int sum = 21; var ts = TwoSum(arr, sum); Console.WriteLine(ts != null ? $"{ts[0]}, {ts[1]}" : "no result"); Console.R...
$numbers = @(0, 2, 11, 19, 90) $sum = 21 $totals = for ($i = 0; $i -lt $numbers.Count; $i++) { for ($j = $numbers.Count-1; $j -ge 0; $j--) { [PSCustomObject]@{ FirstIndex = $i SecondIndex = $j TargetSum = $numbers[$i] + $numbers[$j] } } } $totals | ...
Write the same code in PowerShell as shown below in C#.
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
function last-dayofweek { param( [Int][ValidatePattern("[1-9][0-9][0-9][0-9]")]$year, [String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek ) $date = (Get-Date -Year $year -Month 1 -Day 1) while($date.DayOfWeek -ne $dayofweek) {$date = $date.Ad...
Keep all operations the same but rewrite the snippet in PowerShell.
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
function last-dayofweek { param( [Int][ValidatePattern("[1-9][0-9][0-9][0-9]")]$year, [String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek ) $date = (Get-Date -Year $year -Month 1 -Day 1) while($date.DayOfWeek -ne $dayofweek) {$date = $date.Ad...
Ensure the translated PowerShell code behaves exactly like the original C# snippet.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.E...
function Get-LongestSubsequence ( [int[]]$A ) { If ( $A.Count -lt 2 ) { return $A } $Pile = @( [int]::MaxValue ) $Last = 0 $BP = @{} ForEach ( $N in $A ) { $i = 0..$Last | Where { $N -lt $Pile[$_] } | Select -First 1 $Pile[$...
Ensure the translated PowerShell code behaves exactly like the original C# snippet.
using System; using System.Dynamic; using System.Collections.Generic; public class Program { public static void Main() { string varname = Console.ReadLine(); dynamic expando = new ExpandoObject(); var map = expando as IDictionary<string, object>; map.Add(varname, "Hello...
$variableName = Read-Host New-Variable $variableName 'Foo' Get-Variable $variableName
Translate the given C# code snippet into PowerShell without altering its behavior.
using System; using System.Collections; using System.Collections.Generic; using System.Text; using static System.Linq.Enumerable; public static class BraceExpansion { enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat } const char L = '{', R = '}', S = ','; public static void M...
function Expand-Braces ( [string]$String ) { $Escaped = $False $Stack = New-Object System.Collections.Stack $ClosedBraces = $BracesToParse = $Null ForEach ( $i in 0..($String.Length-1) ) { Switch ( $String[$i] ) { '\' { $Escaped = -not $Escap...
Transform the following C# implementation into PowerShell, maintaining the same output and logic.
XmlReader XReader; XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>")); XReader = XmlReader.Create("xmlfile.xml"); IXPathNavigable XDocument = new XPathDocument(XReader); XPathNavigator Nav = XDocument.CreateNavigator(); Nav = Nav.SelectSingleNode(" if(Nav.MoveToFirst()) { ...
$document = [xml]@' <inventory title="OmniCorp Store <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>Levitation Salve</name...
Translate this program into PowerShell but keep the logic exactly as in C#.
using System; using System.Net; class Program { static void Main(string[] args) { var client = new WebClient(); client.Credentials = CredentialCache.DefaultCredentials; client.Credentials = new NetworkCredential("User", "Password"); var data = client.Download...
$client = [Net.WebClient]::new() $client.Credentials = [Net.CredentialCache]::DefaultCredentials $data = $client.DownloadString("https://example.com") Write-Host $data
Write the same algorithm in PowerShell as shown in this C# implementation.
using System; using System.Collections.Generic; using System.Linq; namespace RankingMethods { class Program { static void Main(string[] args) { Dictionary<string, int> scores = new Dictionary<string, int> { ["Solomon"] = 44, ["Jason"] = 42, ["Erro...
function Get-Ranking { [CmdletBinding(DefaultParameterSetName="Standard")] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string] ...
Change the programming language of this snippet from C# to PowerShell without modifying what it does.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
$Web = New-Object -TypeName Net.Webclient $Words = $web.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt') $IE = $EI = $CIE = $CEI = @() $Clause1 = $Clause2 = $MainClause = $false foreach ($Word in $Words.split()) { switch ($Word) { {($_ -like '*ie*') -and ($_ -notlike '*cie*')}...
Convert this C# block to PowerShell, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
$Web = New-Object -TypeName Net.Webclient $Words = $web.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt') $IE = $EI = $CIE = $CEI = @() $Clause1 = $Clause2 = $MainClause = $false foreach ($Word in $Words.split()) { switch ($Word) { {($_ -like '*ie*') -and ($_ -notlike '*cie*')}...
Ensure the translated PowerShell code behaves exactly like the original C# snippet.
using System.Diagnostics; namespace RC { internal class Program { public static void Main() { string sSource = "Sample App"; string sLog = "Application"; string sEvent = "Hello from RC!"; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);...
$EventLog=new-object System.Diagnostics.EventLog("Application") $EventLog.Source="Application" $infoEvent=[System.Diagnostics.EventLogEntryType]::Information $errorEvent=[System.Diagnostics.EventLogEntryType]::Error $warningEvent=[System.Diagnostics.EventLogEntryType]::Warning $successAuditEvent=[System.Diagnostics...
Write the same code in PowerShell as shown below in C#.
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 2...
function left-factorial ([BigInt]$n) { [BigInt]$k, [BigInt]$fact = ([BigInt]::Zero), ([BigInt]::One) [BigInt]$lfact = ([BigInt]::Zero) while($k -lt $n){ if($k -gt ([BigInt]::Zero)) { $fact = [BigInt]::Multiply($fact, $k) $lfact = [BigInt]::Add($lfact, $fact) }...
Can you help me rewrite this code in PowerShell instead of C#, keeping it the same logically?
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 2...
function left-factorial ([BigInt]$n) { [BigInt]$k, [BigInt]$fact = ([BigInt]::Zero), ([BigInt]::One) [BigInt]$lfact = ([BigInt]::Zero) while($k -lt $n){ if($k -gt ([BigInt]::Zero)) { $fact = [BigInt]::Multiply($fact, $k) $lfact = [BigInt]::Add($lfact, $fact) }...
Convert this C# snippet to PowerShell and keep its semantics consistent.
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); S...
[string]$str = "123" $str.GetType()
Rewrite the snippet below in PowerShell so it works the same as the original C# code.
using SpeechLib; namespace Speaking_Computer { public class Program { private static void Main() { var voice = new SpVoice(); voice.Speak("This is an example of speech synthesis."); } } }
Add-Type -AssemblyName System.Speech $anna = New-Object System.Speech.Synthesis.SpeechSynthesizer $anna.Speak("I'm sorry Dave, I'm afraid I can't do that.") $anna.Dispose()
Please provide an equivalent version of this C# code in PowerShell.
using System; using System.Collections.Generic; using System.Numerics; namespace TonelliShanks { class Solution { private readonly BigInteger root1, root2; private readonly bool exists; public Solution(BigInteger root1, BigInteger root2, bool exists) { this.root1 = root1; ...
Function Invoke-ModuloExponentiation ([BigInt]$Base, [BigInt]$Exponent, $Modulo) { $Result = 1 $Base = $Base % $Modulo If ($Base -eq 0) {return 0} While ($Exponent -gt 0) { If (($Exponent -band 1) -eq 1) {$Result = ($Result * $Base) % $Modulo} $Exponent = $Exponent -shr 1 $B...
Convert the following code from C# to PowerShell, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.Numerics; namespace TonelliShanks { class Solution { private readonly BigInteger root1, root2; private readonly bool exists; public Solution(BigInteger root1, BigInteger root2, bool exists) { this.root1 = root1; ...
Function Invoke-ModuloExponentiation ([BigInt]$Base, [BigInt]$Exponent, $Modulo) { $Result = 1 $Base = $Base % $Modulo If ($Base -eq 0) {return 0} While ($Exponent -gt 0) { If (($Exponent -band 1) -eq 1) {$Result = ($Result * $Base) % $Modulo} $Exponent = $Exponent -shr 1 $B...
Produce a language-to-language conversion: from C# to PowerShell, same semantics.
using System; class Example { public int foo(int x) { return 42 + x; } } class Program { static void Main(string[] args) { var example = new Example(); var method = "foo"; var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5...
$method = ([Math] | Get-Member -MemberType Method -Static | Where-Object {$_.Definition.Split(',').Count -eq 1} | Get-Random).Name $number = (1..9 | Get-Random) / 10 $result = [Math]::$method($number) $output = [PSCustomObject]@{ Method = $method Number = $number Result = $result } $output | Format-List
Write the same code in PowerShell as shown below in C#.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordina...
function CreateGrid($h, $w, $fill) { $grid = 0..($h - 1) | ForEach-Object { , (, $fill * $w) } return $grid } function EstimateCost($a, $b) { $xd = [Math]::Abs($a.Item1 - $b.Item1) $yd = [Math]::Abs($a.Item2 - $b.Item2) return [Math]::Max($xd, $yd) } function AStar($costs, $start, $goal) { ...
Change the following C# code into PowerShell without altering its purpose.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordina...
function CreateGrid($h, $w, $fill) { $grid = 0..($h - 1) | ForEach-Object { , (, $fill * $w) } return $grid } function EstimateCost($a, $b) { $xd = [Math]::Abs($a.Item1 - $b.Item1) $yd = [Math]::Abs($a.Item2 - $b.Item2) return [Math]::Max($xd, $yd) } function AStar($costs, $start, $goal) { ...
Keep all operations the same but rewrite the snippet in PowerShell.
using System; using System.Collections.Generic; using System.Linq; namespace RosettaVectors { public class Vector { public double[] store; public Vector(IEnumerable<double> init) { store = init.ToArray(); } public Vector(double x, double y) { ...
$V1 = New-Object System.Windows.Vector ( 2.5, 3.4 ) $V2 = New-Object System.Windows.Vector ( -6, 2 ) $V1 $V2 $V1 + $V2 $V1 - $V2 $V1 * 3 $V1 / 8
Produce a functionally identical PowerShell code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetPropert...
Get-Date | Get-Member -MemberType Property
Preserve the algorithm and functionality while converting the code from C# to PowerShell.
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b =...
function gauss-jordan-inv([double[][]]$a) { $n = $a.count [double[][]]$b = 0..($n-1) | foreach{[double[]]$row = @(0) * $n; $row[$_] = 1; ,$row} for ($k = 0; $k -lt $n; $k++) { $lmax, $max = $k, [Math]::Abs($a[$k][$k]) for ($l = $k+1; $l -lt $n; $l++) { $tmp = [Math]::Abs($a[$l][...
Generate an equivalent PowerShell version of this C# code.
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b =...
function gauss-jordan-inv([double[][]]$a) { $n = $a.count [double[][]]$b = 0..($n-1) | foreach{[double[]]$row = @(0) * $n; $row[$_] = 1; ,$row} for ($k = 0; $k -lt $n; $k++) { $lmax, $max = $k, [Math]::Abs($a[$k][$k]) for ($l = $k+1; $l -lt $n; $l++) { $tmp = [Math]::Abs($a[$l][...
Convert the following code from Python to Scala, ensuring the logic remains intact.
def jacobi(a, n): if n <= 0: raise ValueError("'n' must be a positive integer.") if n % 2 == 0: raise ValueError("'n' must be odd.") a %= n result = 1 while a != 0: while a % 2 == 0: a /= 2 n_mod_8 = n % 8 if n_mod_8 in (3, 5): ...
fun jacobi(A: Int, N: Int): Int { assert(N > 0 && N and 1 == 1) var a = A % N var n = N var result = 1 while (a != 0) { var aMod4 = a and 3 while (aMod4 == 0) { a = a shr 2 aMod4 = a and 3 } if (aMod4 == 2) { a = a shr 1 ...
Port the following code from Python to Scala with equivalent syntax and logic.
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): ...
typealias Matrix = Array<DoubleArray> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: In...
Port the provided Python code into Scala while preserving the original functionality.
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): ...
typealias Matrix = Array<DoubleArray> fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: In...
Write the same code in Scala as shown below in Python.
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)] >>> len(x) 48 >>> for i in range(0, len(x), (stride:= 10)): print(str(x[i...
fun digitSum(n: Int): Int { var nn = n var sum = 0 while (nn > 0) { sum += (nn % 10) nn /= 10 } return sum } fun main() { var c = 0 for (i in 0 until 1000) { val ds = digitSum(i) if (i.toString().contains(ds.toString())) { print("%3d ".format(i)) ...
Translate the given Python code snippet into Scala without altering its behavior.
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)] >>> len(x) 48 >>> for i in range(0, len(x), (stride:= 10)): print(str(x[i...
fun digitSum(n: Int): Int { var nn = n var sum = 0 while (nn > 0) { sum += (nn % 10) nn /= 10 } return sum } fun main() { var c = 0 for (i in 0 until 1000) { val ds = digitSum(i) if (i.toString().contains(ds.toString())) { print("%3d ".format(i)) ...
Generate a Scala translation of this Python snippet without changing its computational steps.
>>> from random import randrange >>> def sattoloCycle(items): for i in range(len(items) - 1, 0, -1): j = randrange(i) items[j], items[i] = items[i], items[j] >>> >>> for _ in range(10): lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sattoloCycle(lst) print(lst) [5, 8, 1, 2, 6, 4, 3, 9, 10, 7] [5, 9, 8, 10, 4, ...
fun <T> sattolo(items: Array<T>) { for (i in items.size - 1 downTo 1) { val j = (Math.random() * i).toInt() val t = items[i] items[i] = items[j] items[j] = t } } fun main(args: Array<String>) { val items = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22) println...
Transform the following Python implementation into Scala, maintaining the same output and logic.
>>> from random import randrange >>> def sattoloCycle(items): for i in range(len(items) - 1, 0, -1): j = randrange(i) items[j], items[i] = items[i], items[j] >>> >>> for _ in range(10): lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sattoloCycle(lst) print(lst) [5, 8, 1, 2, 6, 4, 3, 9, 10, 7] [5, 9, 8, 10, 4, ...
fun <T> sattolo(items: Array<T>) { for (i in items.size - 1 downTo 1) { val j = (Math.random() * i).toInt() val t = items[i] items[i] = items[j] items[j] = t } } fun main(args: Array<String>) { val items = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22) println...
Produce a language-to-language conversion: from Python to Scala, same semantics.
from ftplib import FTP ftp = FTP('kernel.org') ftp.login() ftp.cwd('/pub/linux/kernel') ftp.set_pasv(True) print ftp.retrlines('LIST') print ftp.retrbinary('RETR README', open('README', 'wb').write) ftp.quit()
import kotlinx.cinterop.* import ftplib.* fun main(args: Array<String>) { val nbuf = nativeHeap.allocPointerTo<netbuf>() FtpInit() FtpConnect("ftp.easynet.fr", nbuf.ptr) val vnbuf = nbuf.value FtpLogin("anonymous", "ftptest@example.com", vnbuf) FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE.toLon...
Keep all operations the same but rewrite the snippet in Scala.
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute() <sqlite3.Cursor object at 0x013265C0> >>>
import java.io.File import java.io.RandomAccessFile fun String.toFixedLength(len: Int) = this.padEnd(len).substring(0, len) class Address( var name: String, var street: String = "", var city: String = "", var state: String = "", var zipCode: String = "", val autoId: Boolean = true ) { va...
Write the same code in Scala as shown below in Python.
def cycleSort(vector): "Sort a vector in place and return the number of writes." writes = 0 for cycleStart, item in enumerate(vector): pos = cycleStart for item2 in vector[cycleStart + 1:]: if item2 < item: pos += 1 if pos == c...
fun <T : Comparable<T>> cycleSort(array: Array<T>): Int { var writes = 0 for (cycleStart in 0 until array.size - 1) { var item = array[cycleStart] var pos = cycleStart for (i in cycleStart + 1 until array.size) if (array[i] < item) pos++ if (pos == cy...
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically?
def cycleSort(vector): "Sort a vector in place and return the number of writes." writes = 0 for cycleStart, item in enumerate(vector): pos = cycleStart for item2 in vector[cycleStart + 1:]: if item2 < item: pos += 1 if pos == c...
fun <T : Comparable<T>> cycleSort(array: Array<T>): Int { var writes = 0 for (cycleStart in 0 until array.size - 1) { var item = array[cycleStart] var pos = cycleStart for (i in cycleStart + 1 until array.size) if (array[i] < item) pos++ if (pos == cy...
Convert this Python block to Scala, preserving its control flow and logic.
primes = [2, 3, 5, 7, 11, 13, 17, 19] def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1 while reasonable_limit < limit: ram_limit = pr...
import java.math.BigInteger import java.util.* fun main() { val input = Scanner(System.`in`) println("Search Size: ") val max = input.nextBigInteger() var counter = 0 var x = BigInteger("3") while (x <= max) { val sqrtNum = x.sqrt().add(BigInteger.ONE) if (x.add(BigInteger.TWO) ...
Keep all operations the same but rewrite the snippet in Scala.
from itertools import count, islice def isBrazil(n): return 7 <= n and ( 0 == n % 2 or any( map(monoDigit(n), range(2, n - 1)) ) ) def monoDigit(n): def go(base): def g(b, n): (q, d) = divmod(n, b) def p(qr): retu...
fun sameDigits(n: Int, b: Int): Boolean { var n2 = n val f = n % b while (true) { n2 /= b if (n2 > 0) { if (n2 % b != f) { return false } } else { break } } return true } fun isBrazilian(n: Int): Boolean { if (n...
Convert this Python snippet to Scala and keep its semantics consistent.
from itertools import count, islice def isBrazil(n): return 7 <= n and ( 0 == n % 2 or any( map(monoDigit(n), range(2, n - 1)) ) ) def monoDigit(n): def go(base): def g(b, n): (q, d) = divmod(n, b) def p(qr): retu...
fun sameDigits(n: Int, b: Int): Boolean { var n2 = n val f = n % b while (true) { n2 /= b if (n2 > 0) { if (n2 % b != f) { return false } } else { break } } return true } fun isBrazilian(n: Int): Boolean { if (n...
Produce a functionally identical Scala code for the snippet given in Python.
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
import java.io.FileWriter fun main(args: Array<String>) { val lp0 = FileWriter("/dev/tape") lp0.write("Hello, world!") lp0.close() }