Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in PHP.
class empty(object): pass e = empty()
class E {}; $e=new E(); $e->foo=1; $e->{"foo"} = 1; // using a runtime name $x = "foo"; $e->$x = 1; // using a runtime name in a variable
Convert this Python block to PHP, preserving its control flow and logic.
class empty(object): pass e = empty()
class E {}; $e=new E(); $e->foo=1; $e->{"foo"} = 1; // using a runtime name $x = "foo"; $e->$x = 1; // using a runtime name in a variable
Generate an equivalent PHP version of this Python code.
class empty(object): pass e = empty()
class E {}; $e=new E(); $e->foo=1; $e->{"foo"} = 1; // using a runtime name $x = "foo"; $e->$x = 1; // using a runtime name in a variable
Change the programming language of this snippet from Python to PHP without modifying what it does.
def perta(atomic) -> (int, int): NOBLES = 2, 10, 18, 36, 54, 86, 118 INTERTWINED = 0, 0, 0, 0, 0, 57, 89 INTERTWINING_SIZE = 14 LINE_WIDTH = 18 prev_noble = 0 for row, noble in enumerate(NOBLES): if atomic <= noble: nb_elem = noble - prev_noble rank = atomic - prev_noble if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE: row += 2 col = rank + 1 else: nb_empty = LINE_WIDTH - nb_elem inside_left_element_rank = 2 if noble > 2 else 1 col = rank + (nb_empty if rank > inside_left_element_rank else 0) break prev_noble = noble return row+1, col TESTS = { 1: (1, 1), 2: (1, 18), 29: (4,11), 42: (5, 6), 58: (8, 5), 59: (8, 6), 57: (8, 4), 71: (8, 18), 72: (6, 4), 89: (9, 4), 90: (9, 5), 103: (9, 18), } for input, out in TESTS.items(): found = perta(input) print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
<?php class PeriodicTable { private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104); private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7); public function rowAndColumn($n) { $i = 7; while ($this->aArray[$i] > $n) $i--; $m = $n + $this->bArray[$i]; return array(floor($m / 18) + 1, $m % 18 + 1); } } $pt = new PeriodicTable(); foreach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) { list($r, $c) = $pt->rowAndColumn($n); echo $n, " -> ", $r, " ", $c, PHP_EOL; } ?>
Please provide an equivalent version of this Python code in PHP.
def perta(atomic) -> (int, int): NOBLES = 2, 10, 18, 36, 54, 86, 118 INTERTWINED = 0, 0, 0, 0, 0, 57, 89 INTERTWINING_SIZE = 14 LINE_WIDTH = 18 prev_noble = 0 for row, noble in enumerate(NOBLES): if atomic <= noble: nb_elem = noble - prev_noble rank = atomic - prev_noble if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE: row += 2 col = rank + 1 else: nb_empty = LINE_WIDTH - nb_elem inside_left_element_rank = 2 if noble > 2 else 1 col = rank + (nb_empty if rank > inside_left_element_rank else 0) break prev_noble = noble return row+1, col TESTS = { 1: (1, 1), 2: (1, 18), 29: (4,11), 42: (5, 6), 58: (8, 5), 59: (8, 6), 57: (8, 4), 71: (8, 18), 72: (6, 4), 89: (9, 4), 90: (9, 5), 103: (9, 18), } for input, out in TESTS.items(): found = perta(input) print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
<?php class PeriodicTable { private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104); private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7); public function rowAndColumn($n) { $i = 7; while ($this->aArray[$i] > $n) $i--; $m = $n + $this->bArray[$i]; return array(floor($m / 18) + 1, $m % 18 + 1); } } $pt = new PeriodicTable(); foreach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) { list($r, $c) = $pt->rowAndColumn($n); echo $n, " -> ", $r, " ", $c, PHP_EOL; } ?>
Keep all operations the same but rewrite the snippet in PHP.
def perta(atomic) -> (int, int): NOBLES = 2, 10, 18, 36, 54, 86, 118 INTERTWINED = 0, 0, 0, 0, 0, 57, 89 INTERTWINING_SIZE = 14 LINE_WIDTH = 18 prev_noble = 0 for row, noble in enumerate(NOBLES): if atomic <= noble: nb_elem = noble - prev_noble rank = atomic - prev_noble if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE: row += 2 col = rank + 1 else: nb_empty = LINE_WIDTH - nb_elem inside_left_element_rank = 2 if noble > 2 else 1 col = rank + (nb_empty if rank > inside_left_element_rank else 0) break prev_noble = noble return row+1, col TESTS = { 1: (1, 1), 2: (1, 18), 29: (4,11), 42: (5, 6), 58: (8, 5), 59: (8, 6), 57: (8, 4), 71: (8, 18), 72: (6, 4), 89: (9, 4), 90: (9, 5), 103: (9, 18), } for input, out in TESTS.items(): found = perta(input) print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
<?php class PeriodicTable { private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104); private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7); public function rowAndColumn($n) { $i = 7; while ($this->aArray[$i] > $n) $i--; $m = $n + $this->bArray[$i]; return array(floor($m / 18) + 1, $m % 18 + 1); } } $pt = new PeriodicTable(); foreach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) { list($r, $c) = $pt->rowAndColumn($n); echo $n, " -> ", $r, " ", $c, PHP_EOL; } ?>
Rewrite this program in PHP while keeping its functionality equivalent to the VB version.
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
Produce a functionally identical PHP code for the snippet given in VB.
Option Explicit Sub DeleteFileOrDirectory() Dim myPath As String myPath = "C:\Users\surname.name\Desktop\Docs" Kill myPath & "\input.txt" RmDir myPath End Sub
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
Convert the following code from VB to PHP, ensuring the logic remains intact.
Dim name as String = "J. Doe" Dim balance as Double = 123.45 Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance) Console.WriteLine(prompt)
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
Can you help me rewrite this code in PHP instead of VB, keeping it the same logically?
Imports System.Math Module RayCasting Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}} Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}} Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}} Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}} Private shapes As Integer()()() = {square, squareHole, strange, hexagon} Public Sub Main() Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}} For Each shape As Integer()() In shapes For Each point As Double() In testPoints Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7))) Next Console.WriteLine() Next End Sub Private Function Contains(shape As Integer()(), point As Double()) As Boolean Dim inside As Boolean = False Dim length As Integer = shape.Length For i As Integer = 0 To length - 1 If Intersects(shape(i), shape((i + 1) Mod length), point) Then inside = Not inside End If Next Return inside End Function Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean If a(1) > b(1) Then Return Intersects(b, a, p) If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001 If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False If p(0) < Min(a(0), b(0)) Then Return True Dim red As Double = (p(1) - a(1)) / (p(0) - a(0)) Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0)) Return red >= blue End Function End Module
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
Generate a PHP translation of this VB snippet without changing its computational steps.
Public Sub Main() Print countSubstring("the three truths", "th") Print countSubstring("ababababab", "abab") Print countSubString("zzzzzzzzzzzzzzz", "z") End Function countSubstring(s As String, search As String) As Integer If s = "" Or search = "" Then Return 0 Dim count As Integer = 0, length As Integer = Len(search) For i As Integer = 1 To Len(s) If Mid(s, i, length) = Search Then count += 1 i += length - 1 End If Next Return count End Function
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
Produce a functionally identical PHP code for the snippet given in VB.
Imports System.IO Module Notes Function Main(ByVal cmdArgs() As String) As Integer Try If cmdArgs.Length = 0 Then Using sr As New StreamReader("NOTES.TXT") Console.WriteLine(sr.ReadToEnd) End Using Else Using sw As New StreamWriter("NOTES.TXT", True) sw.WriteLine(Date.Now.ToString()) sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs)) End Using End If Catch End Try End Function End Module
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
Transform the following VB implementation into PHP, maintaining the same output and logic.
Public Function CommonDirectoryPath(ParamArray Paths()) As String Dim v As Variant Dim Path() As String, s As String Dim i As Long, j As Long, k As Long Const PATH_SEPARATOR As String = "/" For Each v In Paths ReDim Preserve Path(0 To i) Path(i) = v i = i + 1 Next v k = 1 Do For i = 0 To UBound(Path) If i Then If InStr(k, Path(i), PATH_SEPARATOR) <> j Then Exit Do ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then Exit Do End If Else j = InStr(k, Path(i), PATH_SEPARATOR) If j = 0 Then Exit Do End If End If Next i s = Left$(Path(0), j + CLng(k <> 1)) k = j + 1 Loop CommonDirectoryPath = s End Function Sub Main() Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/home/user1/tmp" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members", _ "/home/user1/abc/coven/members") = _ "/home/user1" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/hope/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/" End Sub
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
Write the same algorithm in PHP as shown in this VB implementation.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
<?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 = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Ensure the translated PHP code behaves exactly like the original VB snippet.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
<?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 = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Rewrite this program in PHP while keeping its functionality equivalent to the VB version.
Option Explicit Private Lines(1 To 3, 1 To 3) As String Private Nb As Byte, player As Byte Private GameWin As Boolean, GameOver As Boolean Sub Main_TicTacToe() Dim p As String InitLines printLines Nb Do p = WhoPlay Debug.Print p & " play" If p = "Human" Then Call HumanPlay GameWin = IsWinner("X") Else Call ComputerPlay GameWin = IsWinner("O") End If If Not GameWin Then GameOver = IsEnd Loop Until GameWin Or GameOver If Not GameOver Then Debug.Print p & " Win !" Else Debug.Print "Game Over!" End If End Sub Sub InitLines(Optional S As String) Dim i As Byte, j As Byte Nb = 0: player = 0 For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) Lines(i, j) = "#" Next j Next i End Sub Sub printLines(Nb As Byte) Dim i As Byte, j As Byte, strT As String Debug.Print "Loop " & Nb For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strT = strT & Lines(i, j) Next j Debug.Print strT strT = vbNullString Next i End Sub Function WhoPlay(Optional S As String) As String If player = 0 Then player = 1 WhoPlay = "Human" Else player = 0 WhoPlay = "Computer" End If End Function Sub HumanPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Do L = Application.InputBox("Choose the row", "Numeric only", Type:=1) If L > 0 And L < 4 Then C = Application.InputBox("Choose the column", "Numeric only", Type:=1) If C > 0 And C < 4 Then If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "X" Nb = Nb + 1 printLines Nb GoodPlay = True End If End If End If Loop Until GoodPlay End Sub Sub ComputerPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Randomize Timer Do L = Int((Rnd * 3) + 1) C = Int((Rnd * 3) + 1) If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "O" Nb = Nb + 1 printLines Nb GoodPlay = True End If Loop Until GoodPlay End Sub Function IsWinner(S As String) As Boolean Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String Ch = String(UBound(Lines, 1), S) For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strTL = strTL & Lines(i, j) strTC = strTC & Lines(j, i) Next j If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For strTL = vbNullString: strTC = vbNullString Next i strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3) strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1) If strTL = Ch Or strTC = Ch Then IsWinner = True End Function Function IsEnd() As Boolean Dim i As Byte, j As Byte For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) If Lines(i, j) = "#" Then Exit Function Next j Next i IsEnd = True End Function
<?php const BOARD_NUM = 9; const ROW_NUM = 3; $EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM); function isGameOver($board, $pin) { $pat = '/X{3}|' . //Horz 'X..X..X..|' . //Vert Left '.X..X..X.|' . //Vert Middle '..X..X..X|' . //Vert Right '..X.X.X..|' . //Diag TL->BR 'X...X...X|' . //Diag TR->BL '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); } $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn); echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p]; echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; } echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';
Rewrite the snippet below in PHP so it works the same as the original VB code.
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
Generate a PHP translation of this VB snippet without changing its computational steps.
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
<?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), "\n"; $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; }); echo $factorial(10), "\n"; ?>
Convert the following code from VB to PHP, ensuring the logic remains intact.
Type Contact Name As String firstname As String Age As Byte End Type Function SetContact(N As String, Fn As String, A As Byte) As Contact SetContact.Name = N SetContact.firstname = Fn SetContact.Age = A End Function Sub Test_SetContact() Dim Cont As Contact Cont = SetContact("SMITH", "John", 23) Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old." End Sub
function addsub($x, $y) { return array($x + $y, $x - $y); }
Can you help me rewrite this code in PHP instead of VB, keeping it the same logically?
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Write the same code in PHP as shown below in VB.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Convert this VB snippet to PHP and keep its semantics consistent.
For i = 1 To 10 Console.Write(i) If i Mod 5 = 0 Then Console.WriteLine() Else Console.Write(", ") End If Next
for ($i = 1; $i <= 10; $i++) { echo $i; if ($i % 5 == 0) { echo "\n"; continue; } echo ', '; }
Please provide an equivalent version of this VB code in PHP.
Option Explicit Private Type Choice Number As Integer Name As String End Type Private MaxNumber As Integer Sub Main() Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$ MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1) For i = 1 To 3 U(i) = UserChoice Next For i = 1 To MaxNumber t = vbNullString For j = 1 To 3 If i Mod U(j).Number = 0 Then t = t & U(j).Name Next Debug.Print IIf(t = vbNullString, i, t) Next i End Sub Private Function UserChoice() As Choice Dim ok As Boolean Do While Not ok UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1) UserChoice.Name = InputBox("Enter the corresponding word : ") If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True Loop End Function
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; } ?>
Generate a PHP translation of this VB snippet without changing its computational steps.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
<?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("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Translate the given VB code snippet into PHP without altering its behavior.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
<?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("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Write a version of this VB function in PHP with identical behavior.
Sub Main() Const TESTSTRING As String = "alphaBETA" Debug.Print "initial = " _ & TESTSTRING Debug.Print "uppercase = " _ & UCase(TESTSTRING) Debug.Print "lowercase = " _ & LCase(TESTSTRING) Debug.Print "first letter capitalized = " _ & StrConv(TESTSTRING, vbProperCase) Debug.Print "length (in characters) = " _ & CStr(Len(TESTSTRING)) Debug.Print "length (in bytes) = " _ & CStr(LenB(TESTSTRING)) Debug.Print "reversed = " _ & StrReverse(TESTSTRING) Debug.Print "first position of letter A (case-sensitive) = " _ & InStr(1, TESTSTRING, "A", vbBinaryCompare) Debug.Print "first position of letter A (case-insensitive) = " _ & InStr(1, TESTSTRING, "A", vbTextCompare) Debug.Print "concatenated with & TESTSTRING & "123" End Sub
$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
Generate an equivalent PHP version of this VB code.
Imports System.Security.Cryptography Imports System.Text Module MD5hash Sub Main(args As String()) Console.WriteLine(GetMD5("Visual Basic .Net")) End Sub Private Function GetMD5(plainText As String) As String Dim hash As String = "" Using hashObject As MD5 = MD5.Create() Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText)) Dim hashBuilder As New StringBuilder For i As Integer = 0 To ptBytes.Length - 1 hashBuilder.Append(ptBytes(i).ToString("X2")) Next hash = hashBuilder.ToString End Using Return hash End Function End Module
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
Rewrite this program in PHP while keeping its functionality equivalent to the VB version.
Imports System.Threading Module Module1 Sub SleepSort(items As IEnumerable(Of Integer)) For Each item In items Task.Factory.StartNew(Sub() Thread.Sleep(1000 * item) Console.WriteLine(item) End Sub) Next End Sub Sub Main() SleepSort({1, 5, 2, 1, 8, 10, 3}) Console.ReadKey() End Sub End Module
<?php $buffer = 1; $pids = []; for ($i = 1; $i < $argc; $i++) { $pid = pcntl_fork(); if ($pid < 0) { die("failed to start child process"); } if ($pid === 0) { sleep($argv[$i] + $buffer); echo $argv[$i] . "\n"; exit(); } $pids[] = $pid; } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); }
Generate a PHP translation of this VB snippet without changing its computational steps.
Public Sub LoopsNested() Dim a(1 To 10, 1 To 10) As Integer Randomize For i = 1 To 10 For j = 1 To 10 a(i, j) = Int(20 * Rnd) + 1 Next j Next i For i = 1 To 10 For j = 1 To 10 If a(i, j) <> 20 Then Debug.Print a(i, j), Else i = 10 Exit For End If Next j Debug.Print Next i End Sub
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\n"; ?>
Transform the following VB implementation into PHP, maintaining the same output and logic.
Dim total As Variant, prim As Variant, maxPeri As Variant Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant) Dim p As Variant p = CDec(s0) + CDec(s1) + CDec(s2) If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2 newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2 newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2 End If End Sub Public Sub Program_PythagoreanTriples() maxPeri = CDec(100) Do While maxPeri <= 10000000# prim = CDec(0) total = CDec(0) newTri 3, 4, 5 Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives." maxPeri = maxPeri * 10 Loop End Sub
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Translate this program into PHP but keep the logic exactly as in VB.
Dim total As Variant, prim As Variant, maxPeri As Variant Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant) Dim p As Variant p = CDec(s0) + CDec(s1) + CDec(s2) If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2 newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2 newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2 End If End Sub Public Sub Program_PythagoreanTriples() maxPeri = CDec(100) Do While maxPeri <= 10000000# prim = CDec(0) total = CDec(0) newTri 3, 4, 5 Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives." maxPeri = maxPeri * 10 Loop End Sub
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Port the provided VB code into PHP while preserving the original functionality.
Option Explicit Sub Main() Dim myArr() As Variant, i As Long myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235)) For i = LBound(myArr) To UBound(myArr) Debug.Print myArr(i) Next End Sub Private Function Remove_Duplicate(Arr As Variant) As Variant() Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long ReDim Temp(UBound(Arr)) For i = LBound(Arr) To UBound(Arr) On Error Resume Next myColl.Add CStr(Arr(i)), CStr(Arr(i)) If Err.Number > 0 Then On Error GoTo 0 Else Temp(cpt) = Arr(i) cpt = cpt + 1 End If Next i ReDim Preserve Temp(cpt - 1) Remove_Duplicate = Temp End Function
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
Port the provided VB code into PHP while preserving the original functionality.
function looksay( n ) dim i dim accum dim res dim c res = vbnullstring do if n = vbnullstring then exit do accum = 0 c = left( n,1 ) do while left( n, 1 ) = c accum = accum + 1 n = mid(n,2) loop if accum > 0 then res = res & accum & c end if loop looksay = res end function
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Generate a PHP translation of this VB snippet without changing its computational steps.
Private myStack() Private myStackHeight As Integer Public Function Push(aValue) myStackHeight = myStackHeight + 1 ReDim Preserve myStack(myStackHeight) myStack(myStackHeight) = aValue End Function Public Function Pop() If myStackHeight > 0 Then Pop = myStack(myStackHeight) myStackHeight = myStackHeight - 1 Else MsgBox "Pop: stack is empty!" End If End Function Public Function IsEmpty() As Boolean IsEmpty = (myStackHeight = 0) End Function Property Get Size() As Integer Size = myStackHeight End Property
$stack = array(); empty( $stack ); // true array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2; empty( $stack ); // false echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
Translate this program into PHP but keep the logic exactly as in VB.
Sub C_S_If() Dim A$, B$ A = "Hello" B = "World" If A = B Then Debug.Print A & " = " & B If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B _ Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End Sub
<?php $foo = 3; if ($foo == 2) if ($foo == 3) else if ($foo != 0) { } else { } ?>
Convert this VB block to PHP, preserving its control flow and logic.
type TSettings extends QObject FullName as string FavouriteFruit as string NeedSpelling as integer SeedsRemoved as integer OtherFamily as QStringlist Constructor FullName = "" FavouriteFruit = "" NeedSpelling = 0 SeedsRemoved = 0 OtherFamily.clear end constructor end type Dim Settings as TSettings dim ConfigList as QStringList dim x as integer dim StrLine as string dim StrPara as string dim StrData as string function Trim$(Expr as string) as string Result = Rtrim$(Ltrim$(Expr)) end function Sub ConfigOption(PData as string) dim x as integer for x = 1 to tally(PData, ",") +1 Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x)) next end sub Function ConfigBoolean(PData as string) as integer PData = Trim$(PData) Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0) end function sub ReadSettings ConfigList.LoadFromFile("Rosetta.cfg") ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ") for x = 0 to ConfigList.ItemCount -1 StrLine = Trim$(ConfigList.item(x)) StrPara = Trim$(field$(StrLine," ",1)) StrData = Trim$(lTrim$(StrLine - StrPara)) Select case UCase$(StrPara) case "FULLNAME" : Settings.FullName = StrData case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData) case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData) case "OTHERFAMILY" : Call ConfigOption(StrData) end select next end sub Call ReadSettings
<?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] . '[] = ' . trim($val) . PHP_EOL; } return $r; }, $conf ); $conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf); $ini = parse_ini_string($conf); echo 'Full name = ', $ini['FULLNAME'], PHP_EOL; echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL; echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL; echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL; echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
Convert the following code from VB to PHP, ensuring the logic remains intact.
Imports System Module Sorting_Using_a_Custom_Comparator Function CustomComparator(ByVal x As String, ByVal y As String) As Integer Dim result As Integer result = y.Length - x.Length If result = 0 Then result = String.Compare(x, y, True) End If Return result End Function Sub Main() Dim strings As String() = {"test", "Zoom", "strings", "a"} Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator)) End Sub End Module
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); } $strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); usort($strings, "mycmp"); ?>
Translate this program into PHP but keep the logic exactly as in VB.
Function Selection_Sort(s) arr = Split(s,",") For i = 0 To UBound(arr) For j = i To UBound(arr) temp = arr(i) If arr(j) < arr(i) Then arr(i) = arr(j) arr(j) = temp End If Next Next Selection_Sort = (Join(arr,",")) End Function WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" WScript.StdOut.WriteLine WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1") WScript.StdOut.WriteLine WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
function selection_sort(&$arr) { $n = count($arr); for($i = 0; $i < count($arr); $i++) { $min = $i; for($j = $i + 1; $j < $n; $j++){ if($arr[$j] < $arr[$min]){ $min = $j; } } list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]); } }
Convert the following code from VB to PHP, ensuring the logic remains intact.
Option Explicit Sub Main() Dim arr, i arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next Debug.Print Join(arr, ", ") End Sub Private Function Fibonacci(N) As Variant If N <= 1 Then Fibonacci = N Else Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2) End If End Function
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
Ensure the translated PHP code behaves exactly like the original VB snippet.
Public Sub case_sensitivity() Dim DOG As String DOG = "Benjamin" DOG = "Samba" DOG = "Bernie" Debug.Print "There is just one dog named " & DOG End Sub
<?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";
Please provide an equivalent version of this VB code in PHP.
For i = 10 To 0 Step -1 Debug.Print i Next i
for ($i = 10; $i >= 0; $i--) echo "$i\n";
Change the programming language of this snippet from VB to PHP without modifying what it does.
Option Explicit Const strName As String = "MyFileText.txt" Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _ "The reverse of Read entire file—for when you want to update or " & vbCrLf & _ "create a file which you would read in its entirety all at once." Sub Main() Dim Nb As Integer Nb = FreeFile Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb Print #1, Text Close #Nb End Sub
file_put_contents($filename, $data)
Port the following code from VB to PHP with equivalent syntax and logic.
Public OutConsole As Scripting.TextStream For i = 0 To 4 For j = 0 To i OutConsole.Write "*" Next j OutConsole.WriteLine Next i
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
Preserve the algorithm and functionality while converting the code from VB to PHP.
Imports System Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D Structure bd Public hi, lo As Decimal End Structure Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo), String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo)) If Not comma Then Return r Dim rc As String = "" For i As Integer = r.Length - 3 To 0 Step -3 rc = "," & r.Substring(i, 3) & rc : Next toStr = r.Substring(0, r.Length Mod 3) & rc toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0)) End Function Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _ Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas End Function Sub Main(ByVal args As String()) For p As UInteger = 64 To 95 - 1 Step 30 Dim y As bd, x As bd : a = Pow_dec(2D, p) WriteLine("The square of (2^{0}): {1,38:n0}", p, a) x.hi = Math.Floor(a / hm) : x.lo = a Mod hm Dim BS As BI = BI.Pow(CType(a, BI), 2) y.lo = x.lo * x.lo : y.hi = x.hi * x.hi a = x.hi * x.lo * 2D y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm While y.lo > mx : y.lo -= mx : y.hi += 1 : End While WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf, toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to")) Next End Sub End Module
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
Translate this program into PHP but keep the logic exactly as in VB.
Option Explicit Sub Main_Bulls_and_cows() Dim strNumber As String, strInput As String, strMsg As String, strTemp As String Dim boolEnd As Boolean Dim lngCpt As Long Dim i As Byte, bytCow As Byte, bytBull As Byte Const NUMBER_OF_DIGITS As Byte = 4 Const MAX_LOOPS As Byte = 25 strNumber = Create_Number(NUMBER_OF_DIGITS) Do bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1 If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do strInput = AskToUser(NUMBER_OF_DIGITS) If strInput = "Exit Game" Then strMsg = "User abort": Exit Do For i = 1 To Len(strNumber) If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then bytBull = bytBull + 1 ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then bytCow = bytCow + 1 End If Next i If bytBull = Len(strNumber) Then boolEnd = True: strMsg = "You win in " & lngCpt & " loops!" Else strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows." MsgBox strTemp End If Loop While Not boolEnd MsgBox strMsg End Sub Function Create_Number(NbDigits As Byte) As String Dim myColl As New Collection Dim strTemp As String Dim bytAlea As Byte Randomize Do bytAlea = Int((Rnd * 9) + 1) On Error Resume Next myColl.Add CStr(bytAlea), CStr(bytAlea) If Err <> 0 Then On Error GoTo 0 Else strTemp = strTemp & CStr(bytAlea) End If Loop While Len(strTemp) < NbDigits Create_Number = strTemp End Function Function AskToUser(NbDigits As Byte) As String Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte Do While Not boolGood strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number") If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do If strIn <> "" Then If Len(strIn) = NbDigits Then NbDiff = 0 For i = 1 To Len(strIn) If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then NbDiff = 1 Exit For End If Next i If NbDiff = 0 Then boolGood = True End If End If Loop AskToUser = strIn End Function
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
Write a version of this VB function in PHP with identical behavior.
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sortable.Shuffle() Dim swapped As Boolean Do Dim index, bound As Integer bound = sortable.Ubound While index < bound If sortable(index) > sortable(index + 1) Then Dim s As Integer = sortable(index) sortable.Remove(index) sortable.Insert(index + 1, s) swapped = True End If index = index + 1 Wend Loop Until Not swapped
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
Translate this program into PHP but keep the logic exactly as in VB.
Sub WriteToFile(input As FolderItem, output As FolderItem) Dim tis As TextInputStream Dim tos As TextOutputStream tis = tis.Open(input) tos = tos.Create(output) While Not tis.EOF tos.WriteLine(tis.ReadLine) Wend tis.Close tos.Close End Sub
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
Convert this VB snippet to PHP and keep its semantics consistent.
START: INPUT "Enter two integers (a,b):"; a!, b! IF a = 0 THEN END IF b = 0 THEN PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder." GOTO START END IF PRINT PRINT " Sum = "; a + b PRINT " Difference = "; a - b PRINT " Product = "; a * b PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0." PRINT " Remainder = "; a MOD b, , "* Sign matches first operand." PRINT " Exponentiation = "; a ^ b PRINT INPUT "Again? (y/N)"; a$ IF UCASE$(a$) = "Y" THEN CLS: GOTO START CLS END
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>
Translate the given VB code snippet into PHP without altering its behavior.
Function transpose(m As Variant) As Variant transpose = WorksheetFunction.transpose(m) End Function
function transpose($m) { if (count($m) == 0) // special case: empty matrix return array(); else if (count($m) == 1) // special case: row matrix return array_chunk($m[0], 1); array_unshift($m, NULL); // the original matrix is not modified because it was passed by value return call_user_func_array('array_map', $m); }
Write the same algorithm in PHP as shown in this VB implementation.
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
Produce a functionally identical PHP code for the snippet given in VB.
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
Keep all operations the same but rewrite the snippet in PHP.
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Change the programming language of this snippet from VB to PHP without modifying what it does.
Option Base 1 Private Function sq_add(arr As Variant, x As Double) As Variant Dim res() As Variant ReDim res(UBound(arr)) For i = 1 To UBound(arr) res(i) = arr(i) + x Next i sq_add = res End Function Private Function beadsort(ByVal a As Variant) As Variant Dim poles() As Variant ReDim poles(WorksheetFunction.Max(a)) For i = 1 To UBound(a) For j = 1 To a(i) poles(j) = poles(j) + 1 Next j Next i For j = 1 To UBound(a) a(j) = 0 Next j For i = 1 To UBound(poles) For j = 1 To poles(i) a(j) = a(j) + 1 Next j Next i beadsort = a End Function Public Sub main() Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ") End Sub
<?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) { foreach ($arr as $e) $poles []= array_fill(0, $e, 1); return array_map('count', columns(columns($poles))); } print_r(beadsort(array(5,3,1,7,4,1,1))); ?>
Convert this VB block to PHP, preserving its control flow and logic.
Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim Implems() As String = {"Built-In", "Recursive", "Iterative"}, powers() As Integer = {5, 4, 3, 2} Function intPowR(val As BI, exp As BI) As BI If exp = 0 Then Return 1 Dim ne As BI, vs As BI = val * val If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val End Function Function intPowI(val As BI, exp As BI) As BI intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val val *= val : exp >>= 1 : End While End Function Sub DoOne(title As String, p() As Integer) Dim st As DateTime = DateTime.Now, res As BI, resStr As String Select Case (Array.IndexOf(Implems, title)) Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3)))))) Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3)))) Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3)))) End Select : resStr = res.ToString() Dim et As TimeSpan = DateTime.Now - st Debug.Assert(resStr.Length = 183231) Debug.Assert(resStr.StartsWith("62060698786608744707")) Debug.Assert(resStr.EndsWith("92256259918212890625")) WriteLine("n = {0}", String.Join("^", powers)) WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20)) WriteLine("n digits = {0}", resStr.Length) WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds) End Sub Sub Main() For Each itm As String in Implems : DoOne(itm, powers) : Next If Debugger.IsAttached Then Console.ReadKey() End Sub End Module
<?php $y = bcpow('5', bcpow('4', bcpow('3', '2'))); printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y)); ?>
Keep all operations the same but rewrite the snippet in PHP.
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
Rewrite this program in PHP while keeping its functionality equivalent to the VB version.
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
Generate an equivalent PHP version of this VB code.
Public Sub LoopsBreak() Dim value As Integer Randomize Do While True value = Int(20 * Rnd) Debug.Print value If value = 10 Then Exit Do Debug.Print Int(20 * Rnd) Loop End Sub
while (true) { $a = rand(0,19); echo "$a\n"; if ($a == 10) break; $b = rand(0,19); echo "$b\n"; }
Convert this VB block to PHP, preserving its control flow and logic.
dim s(10) print "Enter 11 numbers." for i = 0 to 10 print i +1; input " => "; s(i) next i print for i = 10 to 0 step -1 print "f("; s(i); ") = "; r = f(s(i)) if r > 400 then print "-=< overflow >=-" else print r end if next i end function f(n) f = sqr(abs(n)) + 5 * n * n * n end function
<?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 = f($s); echo "f(", $s, ") = "; if ($r > 400) echo "overflow\n"; else echo $r, PHP_EOL; } ?>
Produce a language-to-language conversion: from VB to PHP, same semantics.
Option Explicit Sub Main_Middle_three_digits() Dim Numbers, i& Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _ 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) For i = 0 To 16 Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i))) Next End Sub Function Middle3digits(strNb As String) As String If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1) If Len(strNb) < 3 Then Middle3digits = "Error ! Number of digits must be >= 3" ElseIf Len(strNb) Mod 2 = 0 Then Middle3digits = "Error ! Number of digits must be odd" Else Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3) End If End Function
function middlethree($integer) { $int = (int)str_replace('-','',$integer); $length = strlen($int); if(is_int($int)) { if($length >= 3) { if($length % 2 == 1) { $middle = floor($length / 2) - 1; return substr($int,$middle, 3); } else { return 'The value must contain an odd amount of digits...'; } } else { return 'The value must contain at least three digits...'; } } else { return 'The value does not appear to be an integer...'; } } $numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); foreach($numbers as $nums) { echo $nums.' : '.middlethree($nums). '<br>'; }
Change the following VB code into PHP without altering its purpose.
Private Function OddWordFirst(W As String) As String Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String count = 1 Do flag = Not flag l = FindNextPunct(i, W) - count + 1 If flag Then temp = temp & ExtractWord(W, count, l) Else temp = temp & ReverseWord(W, count, l) End If Loop While count < Len(W) OddWordFirst = temp End Function Private Function FindNextPunct(d As Integer, W As String) As Integer Const PUNCT As String = ",;:." Do d = d + 1 Loop While InStr(PUNCT, Mid(W, d, 1)) = 0 FindNextPunct = d End Function Private Function ExtractWord(W As String, c As Integer, i As Integer) As String ExtractWord = Mid(W, c, i) c = c + Len(ExtractWord) End Function Private Function ReverseWord(W As String, c As Integer, i As Integer) As String Dim temp As String, sep As String temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1) sep = Right(Mid(W, c, i), 1) ReverseWord = StrReverse(temp) & sep c = c + Len(ReverseWord) End Function
$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); if (!ctype_alpha($c)) { return $c != "."; } } }; $prev = function(){}; $e = false; while ($e ? $odd($prev) : $even()) { $e = !$e; }
Rewrite this program in PHP while keeping its functionality equivalent to the VB version.
Option Explicit Dim objFSO, DBSource Set objFSO = CreateObject("Scripting.FileSystemObject") DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb" With CreateObject("ADODB.Connection") .Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource .Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_ "CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)" .Close End With
<?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 ) "); ?>
Port the following code from VB to PHP with equivalent syntax and logic.
tt=array( _ "Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _ "Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example") tv=array( _ "A261","A261","G200","G200","H416","H416","L000","L300", _ "M220","P236","R163","R163","R150","T522","S532","E251") For i=lbound(tt) To ubound(tt) ts=soundex(tt(i)) If ts<>tv(i) Then ok=" KO "& tv(i) Else ok="" Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok Next Function getCode(c) Select Case c Case "B", "F", "P", "V" getCode = "1" Case "C", "G", "J", "K", "Q", "S", "X", "Z" getCode = "2" Case "D", "T" getCode = "3" Case "L" getCode = "4" Case "M", "N" getCode = "5" Case "R" getCode = "6" Case "W","H" getCode = "-" End Select End Function Function soundex(s) Dim code, previous, i code = UCase(Mid(s, 1, 1)) previous = getCode(UCase(Mid(s, 1, 1))) For i = 2 To Len(s) current = getCode(UCase(Mid(s, i, 1))) If current <> "" And current <> "-" And current <> previous Then code = code & current If current <> "-" Then previous = current Next soundex = Mid(code & "000", 1, 4) End Function
<?php echo soundex("Soundex"), "\n"; // S532 echo soundex("Example"), "\n"; // E251 echo soundex("Sownteks"), "\n"; // S532 echo soundex("Ekzampul"), "\n"; // E251 ?>
Change the following VB code into PHP without altering its purpose.
Debug.Print "Tom said, ""The fox ran away.""" Debug.Print "Tom said,
'c'; # character 'hello'; # these two strings are the same "hello"; 'Hi $name. How are you?'; # result: "Hi $name. How are you?" "Hi $name. How are you?"; # result: "Hi Bob. How are you?" '\n'; # 2-character string with a backslash and "n" "\n"; # newline character `ls`; # runs a command in the shell and returns the output as a string <<END # Here-Document Hi, whatever goes here gets put into the string, including newlines and $variables, until the label we put above END; <<'END' # Here-Document like single-quoted Same as above, but no interpolation of $variables. END;
Port the following code from VB to PHP with equivalent syntax and logic.
Enum fruits apple banana cherry End Enum Enum fruits2 pear = 5 mango = 10 kiwi = 20 pineapple = 20 End Enum Sub test() Dim f As fruits f = apple Debug.Print "apple equals "; f Debug.Print "kiwi equals "; kiwi Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple End Sub
$fruits = array( "apple", "banana", "cherry" ); $fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 ); class Fruit { const APPLE = 0; const BANANA = 1; const CHERRY = 2; } $value = Fruit::APPLE; define("FRUIT_APPLE", 0); define("FRUIT_BANANA", 1); define("FRUIT_CHERRY", 2);
Port the provided VB code into PHP while preserving the original functionality.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
<?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; case '.': $o .= $d[$_d]; break; case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break; case '[': if((int)ord($d[$_d]) == 0) { $brackets = 1; while($brackets && $_s++ < strlen($s)) { if($s[$_s] == '[') $brackets++; else if($s[$_s] == ']') $brackets--; } } else { $pos = $_s++-1; if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o)) $_s = $pos; } break; case ']': return ((int)ord($d[$_d]) != 0); } } while(++$_s < strlen($s)); } function brainfuck($source, $input='') { $data = array(); $data[0] = chr(0); $data_index = 0; $source_index = 0; $input_index = 0; $output = ''; brainfuck_interpret($source, $source_index, $data, $data_index, $input, $input_index, $output); return $output; } $code = " >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++. "; $inp = '123'; print brainfuck( $code, $inp );
Rewrite the snippet below in PHP so it works the same as the original VB code.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
<?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; case '.': $o .= $d[$_d]; break; case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break; case '[': if((int)ord($d[$_d]) == 0) { $brackets = 1; while($brackets && $_s++ < strlen($s)) { if($s[$_s] == '[') $brackets++; else if($s[$_s] == ']') $brackets--; } } else { $pos = $_s++-1; if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o)) $_s = $pos; } break; case ']': return ((int)ord($d[$_d]) != 0); } } while(++$_s < strlen($s)); } function brainfuck($source, $input='') { $data = array(); $data[0] = chr(0); $data_index = 0; $source_index = 0; $input_index = 0; $output = ''; brainfuck_interpret($source, $source_index, $data, $data_index, $input, $input_index, $output); return $output; } $code = " >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++. "; $inp = '123'; print brainfuck( $code, $inp );
Convert this VB block to PHP, preserving its control flow and logic.
OPTION COMPARE BINARY OPTION EXPLICIT ON OPTION INFER ON OPTION STRICT ON IMPORTS SYSTEM.GLOBALIZATION IMPORTS SYSTEM.TEXT IMPORTS SYSTEM.RUNTIME.INTEROPSERVICES IMPORTS SYSTEM.RUNTIME.COMPILERSERVICES MODULE ARGHELPER READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)() DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN SUB INITIALIZEARGUMENTS(ARGS AS STRING()) FOR EACH ITEM IN ARGS ITEM = ITEM.TOUPPERINVARIANT() IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> """"C THEN DIM COLONPOS = ITEM.INDEXOF(":"C, STRINGCOMPARISON.ORDINAL) IF COLONPOS <> -1 THEN _ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1)) END IF END IF NEXT END SUB SUB FROMARGUMENT(OF T)( KEY AS STRING, <OUT> BYREF VAR AS T, GETDEFAULT AS FUNC(OF T), TRYPARSE AS TRYPARSE(OF STRING, T), OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING) DIM VALUE AS STRING = NOTHING IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN CONSOLE.WRITELINE($"INVALID VALUE FOR {KEY}: {VALUE}") ENVIRONMENT.EXIT(-1) END IF ELSE VAR = GETDEFAULT() END IF END SUB END MODULE MODULE PROGRAM SUB MAIN(ARGS AS STRING()) DIM DT AS DATE DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN INITIALIZEARGUMENTS(ARGS) FROMARGUMENT("DATE", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE) FROMARGUMENT("COLS", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20) FROMARGUMENT("ROWS", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0) FROMARGUMENT("MS/ROW", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \ 20) FROMARGUMENT("VSTRETCH", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE) FROMARGUMENT("HSTRETCH", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE) FROMARGUMENT("WSIZE", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE) IF RESIZEWINDOW THEN CONSOLE.WINDOWWIDTH = COLUMNS + 1 CONSOLE.WINDOWHEIGHT = ROWS END IF IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \ 22, 1) FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH) CONSOLE.WRITE(ROW) NEXT END SUB ITERATOR FUNCTION GETCALENDARROWS( DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, MONTHSPERROW AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING) DIM YEAR = DT.YEAR DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW)) DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3 YIELD "[SNOOPY]".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE YIELD ENVIRONMENT.NEWLINE DIM MONTH = 0 DO WHILE MONTH < 12 DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12) DIM CELLWIDTH = WIDTH \ MONTHSPERROW DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \ 20) DIM CELLHEIGHT = MONTHGRIDHEIGHT \ CALENDARROWCOUNT DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \ 20 DIM GETMONTHFROM = FUNCTION(M AS INTEGER) BUILDMONTH( DT:=NEW DATE(DT.YEAR, M, 1), WIDTH:=CELLCONTENTWIDTH, HEIGHT:=CELLCONTENTHEIGHT, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH)) DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) = ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM) DIM CALENDARROW AS IENUMERABLE(OF STRING) = INTERLEAVED( MONTHSTHISROW, USEINNERSEPARATOR:=FALSE, USEOUTERSEPARATOR:=TRUE, OUTERSEPARATOR:=ENVIRONMENT.NEWLINE) DIM EN = CALENDARROW.GETENUMERATOR() DIM HASNEXT = EN.MOVENEXT() DO WHILE HASNEXT DIM CURRENT AS STRING = EN.CURRENT HASNEXT = EN.MOVENEXT() YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE) LOOP MONTH += MONTHSPERROW LOOP END FUNCTION ITERATOR FUNCTION INTERLEAVED(OF T)( SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)), OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE, OPTIONAL INNERSEPARATOR AS T = NOTHING, OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE, OPTIONAL OUTERSEPARATOR AS T = NOTHING, OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T) DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING TRY SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY() DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN DIM ANYPREVITERS AS BOOLEAN = FALSE DO DIM FIRSTACTIVE = -1, LASTACTIVE = -1 FOR I = 0 TO NUMSOURCES - 1 ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT() IF ENUMERATORSTATES(I) THEN IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I LASTACTIVE = I END IF NEXT DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1) IF NOT THISITERHASRESULTS THEN EXIT DO IF ANYPREVITERS THEN IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR ELSE ANYPREVITERS = TRUE END IF FOR I = 0 TO NUMSOURCES - 1 IF ENUMERATORSTATES(I) THEN IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR YIELD SOURCEENUMERATORS(I).CURRENT END IF NEXT LOOP FINALLY IF SOURCEENUMERATORS ISNOT NOTHING THEN FOR EACH EN IN SOURCEENUMERATORS EN.DISPOSE() NEXT END IF END TRY END FUNCTION ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING) CONST DAY_WDT = 2 CONST ALLDAYS_WDT = DAY_WDT * 7 DT = NEW DATE(DT.YEAR, DT.MONTH, 1) DIM DAYSEP AS NEW STRING(" "C, MATH.MIN((WIDTH - ALLDAYS_WDT) \ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1))) DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \ 7) DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6 DIM LEFTPAD AS NEW STRING(" "C, (WIDTH - BLOCKWIDTH) \ 2) DIM FULLPAD AS NEW STRING(" "C, WIDTH) DIM SB AS NEW STRINGBUILDER(LEFTPAD) DIM NUMLINES = 0 DIM ENDLINE = FUNCTION() AS IENUMERABLE(OF STRING) DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH) SB.CLEAR() SB.APPEND(LEFTPAD) RETURN IF(NUMLINES >= HEIGHT, ENUMERABLE.EMPTY(OF STRING)(), ITERATOR FUNCTION() AS IENUMERABLE(OF STRING) YIELD FINISHEDLINE NUMLINES += 1 FOR I = 1 TO VERTBLANKCOUNT IF NUMLINES >= HEIGHT THEN RETURN YIELD FULLPAD NUMLINES += 1 NEXT END FUNCTION()) END FUNCTION SB.APPEND(PADCENTER(DT.TOSTRING("MMMM", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER()) FOR EACH L IN ENDLINE() YIELD L NEXT DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER()) SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS)) FOR EACH L IN ENDLINE() YIELD L NEXT DIM STARTWKDY = CINT(DT.DAYOFWEEK) DIM FIRSTPAD AS NEW STRING(" "C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY) SB.APPEND(FIRSTPAD) DIM D = DT DO WHILE D.MONTH = DT.MONTH SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $"{{0,{DAY_WDT}}}", D.DAY) IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN FOR EACH L IN ENDLINE() YIELD L NEXT ELSE SB.APPEND(DAYSEP) END IF D = D.ADDDAYS(1) LOOP DIM NEXTLINES AS IENUMERABLE(OF STRING) DO NEXTLINES = ENDLINE() FOR EACH L IN NEXTLINES YIELD L NEXT LOOP WHILE NEXTLINES.ANY() END FUNCTION <EXTENSION()> PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = " "C) AS STRING RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR) END FUNCTION END MODULE
<?PHP ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT JANUARY FEBRUARY MARCH APRIL MAY JUNE MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO 1 2 3 4 5 1 2 1 2 1 2 3 4 5 6 1 2 3 4 1 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 31 30 JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31 REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT ; // MAGICAL SEMICOLON
Convert this VB snippet to PHP and keep its semantics consistent.
Function mtf_encode(s) Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 1 To Len(s) char = Mid(s,i,1) If i = Len(s) Then output = output & symbol_table.IndexOf(char,0) symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char Else output = output & symbol_table.IndexOf(char,0) & " " symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_encode = output End Function Function mtf_decode(s) code = Split(s," ") Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 0 To UBound(code) char = symbol_table(code(i)) output = output & char If code(i) <> 0 Then symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_decode = output End Function wordlist = Array("broood","bananaaa","hiphophiphop") For Each word In wordlist WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_ mtf_decode(mtf_encode(word)) & "." WScript.StdOut.WriteBlankLines(1) Next
<?php function symbolTable() { $symbol = array(); for ($c = ord('a') ; $c <= ord('z') ; $c++) { $symbol[$c - ord('a')] = chr($c); } return $symbol; } function mtfEncode($original, $symbol) { $encoded = array(); for ($i = 0 ; $i < strlen($original) ; $i++) { $char = $original[$i]; $position = array_search($char, $symbol); $encoded[] = $position; $mtf = $symbol[$position]; unset($symbol[$position]); array_unshift($symbol, $mtf); } return $encoded; } function mtfDecode($encoded, $symbol) { $decoded = ''; foreach ($encoded AS $position) { $char = $symbol[$position]; $decoded .= $char; unset($symbol[$position]); array_unshift($symbol, $char); } return $decoded; } foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) { $encoded = mtfEncode($original, symbolTable()); $decoded = mtfDecode($encoded, symbolTable()); echo $original, ' -> [', implode(',', $encoded), ']', ' -> ', $decoded, ' : ', ($original === $decoded ? 'OK' : 'Error'), PHP_EOL; }
Maintain the same structure and functionality when rewriting this code in PHP.
Set objShell = CreateObject("WScript.Shell") objShell.Run "%comspec% /K dir",3,True
@exec($command,$output); echo nl2br($output);
Maintain the same structure and functionality when rewriting this code in PHP.
Option explicit Function fileexists(fn) fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn) End Function Function xmlvalid(strfilename) Dim xmldoc,xmldoc2,objSchemas Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0") If fileexists(Replace(strfilename,".xml",".dtd")) Then xmlDoc.setProperty "ProhibitDTD", False xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then xmlDoc.setProperty "ProhibitDTD", True xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0") xmlDoc2.validateOnParse = True xmlDoc2.async = False xmlDoc2.load(Replace (strfilename,".xml",".xsd")) Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0") objSchemas.Add "", xmlDoc2 Else Set xmlvalid= Nothing:Exit Function End If Set xmlvalid=xmldoc.parseError End Function Sub displayerror (parserr) Dim strresult If parserr is Nothing Then strresult= "could not find dtd or xsd for " & strFileName Else With parserr Select Case .errorcode Case 0 strResult = "Valid: " & strFileName & vbCr Case Else strResult = vbCrLf & "ERROR! Failed to validate " & _ strFileName & vbCrLf &.reason & vbCr & _ "Error code: " & .errorCode & ", Line: " & _ .line & ", Character: " & _ .linepos & ", Source: """ & _ .srcText & """ - " & vbCrLf End Select End With End If WScript.Echo strresult End Sub Dim strfilename strfilename="shiporder.xml" displayerror xmlvalid (strfilename)
libxml_use_internal_errors(true); $xml = new DOMDocument(); $xml->load('shiporder.xml'); if (!$xml->schemaValidate('shiporder.xsd')) { var_dump(libxml_get_errors()); exit; } else { echo 'success'; }
Transform the following VB implementation into PHP, maintaining the same output and logic.
Sub Lis(arr() As Integer) Dim As Integer lb = Lbound(arr), ub = Ubound(arr) Dim As Integer i, lo, hi, mitad, newl, l = 0 Dim As Integer p(ub), m(ub) For i = lb To ub lo = 1 hi = l Do While lo <= hi mitad = Int((lo+hi)/2) If arr(m(mitad)) < arr(i) Then lo = mitad + 1 Else hi = mitad - 1 End If Loop newl = lo p(i) = m(newl-1) m(newl) = i If newL > l Then l = newl Next i Dim As Integer res(l) Dim As Integer k = m(l) For i = l-1 To 0 Step - 1 res(i) = arr(k) k = p(k) Next i For i = Lbound(res) To Ubound(res)-1 Print res(i); " "; Next i End Sub Dim As Integer arrA(5) => {3,2,6,4,5,1} Lis(arrA()) Print Dim As Integer arrB(15) => {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15} Lis(arrB()) Sleep
<?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) $high = $mid - 1; else $low = $mid + 1; } $i = $low; $node = new Node(); $node->val = $x; if ($i != 0) $node->back = $pileTops[$i-1]; $pileTops[$i] = $node; } $result = array(); for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL; $node != NULL; $node = $node->back) $result[] = $node->val; return array_reverse($result); } print_r(lis(array(3, 2, 6, 4, 5, 1))); print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15))); ?>
Produce a language-to-language conversion: from VB to PHP, same semantics.
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If String.IsNullOrEmpty(s) Then Exit While End If out.AddRange(g) If s(0) = "}" Then If comma Then Return Tuple.Create(out, s.Substring(1)) End If Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1)) End If If s(0) = "," Then comma = True s = s.Substring(1) End If End While Return Nothing End Function Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String) Dim out As New List(Of String) From {""} While Not String.IsNullOrEmpty(s) Dim c = s(0) If depth > 0 AndAlso (c = "," OrElse c = "}") Then Return Tuple.Create(out, s) End If If c = "{" Then Dim x = GetGroup(s.Substring(1), depth + 1) If Not IsNothing(x) Then Dim tout As New List(Of String) For Each a In out For Each b In x.Item1 tout.Add(a + b) Next Next out = tout s = x.Item2 Continue While End If End If If c = "\" AndAlso s.Length > 1 Then c += s(1) s = s.Substring(1) End If out = out.Select(Function(a) a + c).ToList() s = s.Substring(1) End While Return Tuple.Create(out, s) End Function Sub Main() For Each s In { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\, again\, }}more }cowbell!", "{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" } Dim fmt = "{0}" + vbNewLine + vbTab + "{1}" Dim parts = GetItem(s) Dim res = String.Join(vbNewLine + vbTab, parts.Item1) Console.WriteLine(fmt, s, res) Next End Sub End Module
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 = []; foreach($out as $a) { foreach($x[0] as $b) { $tmp[] = $a . $b; } } $out = $tmp; $s = $x[1]; continue; } } if ($c == '\\' && strlen($s) > 1) { list($s, $c) = [substr($s, 1), ($c . $s[1])]; } $tmp = []; foreach($out as $a) { $tmp[] = $a . $c; } $out = $tmp; $s = substr($s, 1); } return [$out, $s]; } function getgroup($s,$depth) { list($out, $comma) = [[], false]; while ($s) { list($g, $s) = getitem($s, $depth); if (!$s) { break; } $out = array_merge($out, $g); if ($s[0] == '}') { if ($comma) { return [$out, substr($s, 1)]; } $tmp = []; foreach($out as $a) { $tmp[] = '{' . $a . '}'; } return [$tmp, substr($s, 1)]; } if ($s[0] == ',') { list($comma, $s) = [true, substr($s, 1)]; } } return null; } $lines = <<< 'END' ~/{Downloads,Pictures}/*.{jpg,gif,png} It{{em,alic}iz,erat}e{d,}, please. {,{,gotta have{ ,\, again\, }}more }cowbell! {}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\} END; foreach( explode("\n", $lines) as $line ) { printf("\n%s\n", $line); foreach( getitem($line)[0] as $expansion ) { printf(" %s\n", $expansion); } }
Port the following code from VB to PHP with equivalent syntax and logic.
Function IsSelfDescribing(n) IsSelfDescribing = False Set digit = CreateObject("Scripting.Dictionary") For i = 1 To Len(n) k = Mid(n,i,1) If digit.Exists(k) Then digit.Item(k) = digit.Item(k) + 1 Else digit.Add k,1 End If Next c = 0 For j = 0 To Len(n)-1 l = Mid(n,j+1,1) If digit.Exists(CStr(j)) Then If digit.Item(CStr(j)) = CInt(l) Then c = c + 1 End If ElseIf l = 0 Then c = c + 1 Else Exit For End If Next If c = Len(n) Then IsSelfDescribing = True End If End Function start_time = Now s = "" For m = 1 To 100000000 If IsSelfDescribing(m) Then WScript.StdOut.WriteLine m End If Next end_time = Now WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
<?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; } } ?>
Convert this VB snippet to PHP and keep its semantics consistent.
Private Function mul_inv(a As Long, n As Long) As Variant If n < 0 Then n = -n If a < 0 Then a = n - ((-a) Mod n) Dim t As Long: t = 0 Dim nt As Long: nt = 1 Dim r As Long: r = n Dim nr As Long: nr = a Dim q As Long Do While nr <> 0 q = r \ nr tmp = t t = nt nt = tmp - q * nt tmp = r r = nr nr = tmp - q * nr Loop If r > 1 Then mul_inv = "a is not invertible" Else If t < 0 Then t = t + n mul_inv = t End If End Function Public Sub mi() Debug.Print mul_inv(42, 2017) Debug.Print mul_inv(40, 1) Debug.Print mul_inv(52, -217) Debug.Print mul_inv(-486, 217) Debug.Print mul_inv(40, 2018) End Sub
<?php function invmod($a,$n){ if ($n < 0) $n = -$n; if ($a < 0) $a = $n - (-$a % $n); $t = 0; $nt = 1; $r = $n; $nr = $a % $n; while ($nr != 0) { $quot= intval($r/$nr); $tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp; $tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp; } if ($r > 1) return -1; if ($t < 0) $t += $n; return $t; } printf("%d\n", invmod(42, 2017)); ?>
Transform the following VB implementation into PHP, maintaining the same output and logic.
Class HTTPSock Inherits TCPSocket Event Sub DataAvailable() Dim headers As New InternetHeaders headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!"))) headers.AppendHeader("Content-Type", "text/plain") headers.AppendHeader("Content-Encoding", "identity") headers.AppendHeader("Connection", "close") Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!" Me.Write(data) Me.Close End Sub End Class Class HTTPServ Inherits ServerSocket Event Sub AddSocket() As TCPSocket Return New HTTPSock End Sub End Class Class App Inherits Application Event Sub Run(Args() As String) Dim sock As New HTTPServ sock.Port = 8080 sock.Listen() While True App.DoEvents Wend End Sub End Class
<?php $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!'); socket_bind($socket, 0, 8080); socket_listen($socket); $msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>'; for (;;) { if ($client = @socket_accept($socket)) { socket_write($client, "HTTP/1.1 200 OK\r\n" . "Content-length: " . strlen($msg) . "\r\n" . "Content-Type: text/html; charset=UTF-8\r\n\r\n" . $msg); } else usleep(100000); // limits CPU usage by sleeping after doing every request } ?>
Ensure the translated PHP code behaves exactly like the original VB snippet.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With Set objFSO = Nothing Set objParamLookup = Nothing
<?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', $conf, $matches)) { $conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf); } else { $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL; } echo $conf;
Produce a language-to-language conversion: from VB to PHP, same semantics.
Sub Main() Dim d As Double Dim s As Single d = -12.3456 d = 1000# d = 0.00001 d = 67# d = 8.9 d = 0.33 d = 0# d = 2# * 10 ^ 3 d = 2E+50 d = 2E-50 s = -12.3456! s = 1000! s = 0.00001! s = 67! s = 8.9! s = 0.33! s = 0! s = 2! * 10 ^ 3 End Sub
.12 0.1234 1.2e3 7E-10
Change the following VB code into PHP without altering its purpose.
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
<?php class SimpleClass { private $answer = "hello\"world\nforever :)"; } $class = new SimpleClass; ob_start(); var_export($class); $class_content = ob_get_clean(); $class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content); $class_content = preg_replace('"\)$"', ';', $class_content); $new_class = eval($class_content); echo $new_class['answer'];
Ensure the translated PHP code behaves exactly like the original VB snippet.
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
<?php class SimpleClass { private $answer = "hello\"world\nforever :)"; } $class = new SimpleClass; ob_start(); var_export($class); $class_content = ob_get_clean(); $class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content); $class_content = preg_replace('"\)$"', ';', $class_content); $new_class = eval($class_content); echo $new_class['answer'];
Produce a functionally identical PHP code for the snippet given in VB.
Public Sub Main() For y As Integer = 2000 To 2100 If isLongYear(y) Then Print y, Next End Function p(y As Integer) As Integer Return (y + (y \ 4) - (y \ 100) + (y \ 400)) Mod 7 End Function Function isLongYear(y As Integer) As Boolean If p(y) = 4 Then Return True If p(y - 1) = 3 Then Return True Return False End Function
function isLongYear($year) { return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year))); } for ($y=1995; $y<=2045; ++$y) { if (isLongYear($y)) { printf("%s\n", $y); } }
Rewrite this program in PHP while keeping its functionality equivalent to the VB version.
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
Change the programming language of this snippet from VB to PHP without modifying what it does.
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
Ensure the translated PHP code behaves exactly like the original VB snippet.
Class Branch Public from As Node Public towards As Node Public length As Integer Public distance As Integer Public key As String Class Node Public key As String Public correspondingBranch As Branch Const INFINITY = 32767 Private Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node) Dim a As New Collection Dim b As New Collection Dim c As New Collection Dim I As New Collection Dim II As New Collection Dim III As New Collection Dim u As Node, R_ As Node, dist As Integer For Each n In Nodes c.Add n, n.key Next n For Each e In Branches III.Add e, e.key Next e a.Add P, P.key c.Remove P.key Set u = P Do For Each r In III If r.from Is u Then Set R_ = r.towards If Belongs(R_, c) Then c.Remove R_.key b.Add R_, R_.key Set R_.correspondingBranch = r If u.correspondingBranch Is Nothing Then R_.correspondingBranch.distance = r.length Else R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If III.Remove r.key II.Add r, r.key Else If Belongs(R_, b) Then If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then II.Remove R_.correspondingBranch.key II.Add r, r.key Set R_.correspondingBranch = r R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If End If End If End If Next r dist = INFINITY Set u = Nothing For Each n In b If dist > n.correspondingBranch.distance Then dist = n.correspondingBranch.distance Set u = n End If Next n b.Remove u.key a.Add u, u.key II.Remove u.correspondingBranch.key I.Add u.correspondingBranch, u.correspondingBranch.key Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q) If Not Q Is Nothing Then GetPath Q End Sub Private Function Belongs(n As Node, col As Collection) As Boolean Dim obj As Node On Error GoTo err Belongs = True Set obj = col(n.key) Exit Function err: Belongs = False End Function Private Sub GetPath(Target As Node) Dim path As String If Target.correspondingBranch Is Nothing Then path = "no path" Else path = Target.key Set u = Target Do While Not u.correspondingBranch Is Nothing path = u.correspondingBranch.from.key & " " & path Set u = u.correspondingBranch.from Loop Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path End If End Sub Public Sub test() Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = "ab": ab.distance = INFINITY Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = "ac": ac.distance = INFINITY Set af.from = a: Set af.towards = f: af.length = 14: af.key = "af": af.distance = INFINITY Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = "bc": bc.distance = INFINITY Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = "bd": bd.distance = INFINITY Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = "cd": cd.distance = INFINITY Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = "cf": cf.distance = INFINITY Set de.from = d: Set de.towards = e: de.length = 6: de.key = "de": de.distance = INFINITY Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = "ef": ef.distance = INFINITY a.key = "a" b.key = "b" c.key = "c" d.key = "d" e.key = "e" f.key = "f" Dim testNodes As New Collection Dim testBranches As New Collection testNodes.Add a, "a" testNodes.Add b, "b" testNodes.Add c, "c" testNodes.Add d, "d" testNodes.Add e, "e" testNodes.Add f, "f" testBranches.Add ab, "ab" testBranches.Add ac, "ac" testBranches.Add af, "af" testBranches.Add bc, "bc" testBranches.Add bd, "bd" testBranches.Add cd, "cd" testBranches.Add cf, "cf" testBranches.Add de, "de" testBranches.Add ef, "ef" Debug.Print "From", "To", "Distance", "Path" Dijkstra testNodes, testBranches, a, e Dijkstra testNodes, testBranches, a GetPath f End Sub
<?php function dijkstra($graph_array, $source, $target) { $vertices = array(); $neighbours = array(); foreach ($graph_array as $edge) { array_push($vertices, $edge[0], $edge[1]); $neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]); $neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]); } $vertices = array_unique($vertices); foreach ($vertices as $vertex) { $dist[$vertex] = INF; $previous[$vertex] = NULL; } $dist[$source] = 0; $Q = $vertices; while (count($Q) > 0) { $min = INF; foreach ($Q as $vertex){ if ($dist[$vertex] < $min) { $min = $dist[$vertex]; $u = $vertex; } } $Q = array_diff($Q, array($u)); if ($dist[$u] == INF or $u == $target) { break; } if (isset($neighbours[$u])) { foreach ($neighbours[$u] as $arr) { $alt = $dist[$u] + $arr["cost"]; if ($alt < $dist[$arr["end"]]) { $dist[$arr["end"]] = $alt; $previous[$arr["end"]] = $u; } } } } $path = array(); $u = $target; while (isset($previous[$u])) { array_unshift($path, $u); $u = $previous[$u]; } array_unshift($path, $u); return $path; } $graph_array = array( array("a", "b", 7), array("a", "c", 9), array("a", "f", 14), array("b", "c", 10), array("b", "d", 15), array("c", "d", 11), array("c", "f", 2), array("d", "e", 6), array("e", "f", 9) ); $path = dijkstra($graph_array, "a", "e"); echo "path is: ".implode(", ", $path)."\n";
Convert this VB block to PHP, preserving its control flow and logic.
Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 For Each s In h.Keys Debug.Print s Next For Each s In h.Items Debug.Print s Next u = h.Keys v = h.Items For i = 0 To h.Count - 1 Debug.Print u(i), v(i) Next End Sub
<?php $pairs = array( "hello" => 1, "world" => 2, "!" => 3 ); foreach($pairs as $k => $v) { echo "(k,v) = ($k, $v)\n"; } foreach(array_keys($pairs) as $key) { echo "key = $key, value = $pairs[$key]\n"; } foreach($pairs as $value) { echo "values = $value\n"; } ?>
Can you help me rewrite this code in PHP instead of VB, keeping it the same logically?
Dim t_age(4,1) t_age(0,0) = 27 : t_age(0,1) = "Jonah" t_age(1,0) = 18 : t_age(1,1) = "Alan" t_age(2,0) = 28 : t_age(2,1) = "Glory" t_age(3,0) = 18 : t_age(3,1) = "Popeye" t_age(4,0) = 28 : t_age(4,1) = "Alan" Dim t_nemesis(4,1) t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders" t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts" t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies" t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy" Call hash_join(t_age,1,t_nemesis,0) Sub hash_join(table_1,index_1,table_2,index_2) Set hash = CreateObject("Scripting.Dictionary") For i = 0 To UBound(table_1) hash.Add i,Array(table_1(i,0),table_1(i,1)) Next For j = 0 To UBound(table_2) For Each key In hash.Keys If hash(key)(index_1) = table_2(j,index_2) Then WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_ " = " & table_2(j,0) & "," & table_2(j,1) End If Next Next End Sub
<?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"), array(28, "Glory"), array(18, "Popeye"), array(28, "Alan")); $table2 = array(array("Jonah", "Whales"), array("Jonah", "Spiders"), array("Alan", "Ghosts"), array("Alan", "Zombies"), array("Glory", "Buffy"), array("Bob", "foo")); foreach (hashJoin($table1, 1, $table2, 0) as $row) print_r($row); ?>
Convert the following code from VB to PHP, ensuring the logic remains intact.
Class Animal End Class Class Dog Inherits Animal End Class Class Lab Inherits Dog End Class Class Collie Inherits Dog End Class Class Cat Inherits Animal End Class
class Animal { } class Dog extends Animal { } class Cat extends Animal { } class Lab extends Dog { } class Collie extends Dog { }
Write a version of this VB function in PHP with identical behavior.
Option Explicit Sub Test() Dim h As Object Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 Debug.Print h.Item("A") h.Item("C") = 4 h.Key("C") = "D" Debug.Print h.exists("C") h.Remove "B" Debug.Print h.Count h.RemoveAll Debug.Print h.Count End Sub
$array = array(); $array = []; // Simpler form of array initialization $array['foo'] = 'bar'; $array['bar'] = 'foo'; echo($array['foo']); // bar echo($array['moo']); // Undefined index $array2 = array('fruit' => 'apple', 'price' => 12.96, 'colour' => 'green'); $array2 = ['fruit' => 'apple', 'price' => 12.96, 'colour' => 'green']; echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
Preserve the algorithm and functionality while converting the code from VB to PHP.
Imports System.Reflection Module Module1 Class TestClass Private privateField = 7 Public ReadOnly Property PublicNumber = 4 Private ReadOnly Property PrivateNumber = 2 End Class Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return From p In obj.GetType().GetProperties(flags) Where p.GetIndexParameters().Length = 0 Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)} End Function Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)}) End Function Sub Main() Dim t As New TestClass() Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance For Each prop In GetPropertyValues(t, flags) Console.WriteLine(prop) Next For Each field In GetFieldValues(t, flags) Console.WriteLine(field) Next End Sub End Module
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
Translate the given VB code snippet into PHP without altering its behavior.
Dim MText as QMemorystream MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" MText.WriteLine "are$delineated$by$a$single$ MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" MText.WriteLine "column$are$separated$by$at$least$one$space." MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$" MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column." DefStr TextLeft, TextRight, TextCenter DefStr MLine, LWord, Newline = chr$(13)+chr$(10) DefInt ColWidth(100), ColCount DefSng NrSpaces MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y)) next next MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) NrSpaces = ColWidth(y) - len(LWord) TextLeft = TextLeft + LWord + Space$(NrSpaces+1) TextRight = TextRight + Space$(NrSpaces+1) + LWord TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2)) next TextLeft = TextLeft + Newline TextRight = TextRight + Newline TextCenter = TextCenter + Newline next
<?php $j2justtype = array('L' => STR_PAD_RIGHT, 'R' => STR_PAD_LEFT, 'C' => STR_PAD_BOTH); function aligner($str, $justification = 'L') { global $j2justtype; assert(array_key_exists($justification, $j2justtype)); $justtype = $j2justtype[$justification]; $fieldsbyrow = array(); foreach (explode("\n", $str) as $line) $fieldsbyrow[] = explode('$', $line); $maxfields = max(array_map('count', $fieldsbyrow)); foreach (range(0, $maxfields - 1) as $col) { $maxwidth = 0; foreach ($fieldsbyrow as $fields) $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0)); foreach ($fieldsbyrow as &$fields) $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype); unset($fields); // see http://bugs.php.net/29992 } $result = ''; foreach ($fieldsbyrow as $fields) $result .= implode(' ', $fields) . "\n"; return $result; } $textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$\'dollar\'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.'; foreach (array('L', 'R', 'C') as $j) echo aligner($textinfile, $j); ?>
Maintain the same structure and functionality when rewriting this code in PHP.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
Preserve the algorithm and functionality while converting the code from VB to PHP.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
Can you help me rewrite this code in PHP instead of VB, keeping it the same logically?
Dim variable As datatype Dim var1,var2,... As datatype
<?php # NULL typed variable $null = NULL; var_dump($null); // output: null # defining a boolean $boolean = true; var_dump($boolean); // output: boolean true $boolean = false; var_dump($boolean); // output: boolean false # bool and boolean is the same $boolean = (bool)1; var_dump($boolean); // output: boolean true $boolean = (boolean)1; var_dump($boolean); // output: boolean true $boolean = (bool)0; var_dump($boolean); // output: boolean false $boolean = (boolean)0; var_dump($boolean); // output: boolean false # defining an integer $int = 0; var_dump($int); // output: int 0 # defining a float, $float = 0.01; var_dump($float); // output: float 0.01 # which is also identical to "real" and "double" var_dump((double)$float); // output: float 0.01 var_dump((real)$float); // output: float 0.01 # casting back to int (auto flooring the value) var_dump((int)$float); // output: int 0 var_dump((int)($float+1)); // output: int 1 var_dump((int)($float+1.9)); // output: int 1 # defining a string $string = 'string'; var_dump($string); // output: string 'string' (length=6) # referencing a variable (there are no pointers in PHP). $another_string = &$string; var_dump($another_string); $string = "I'm the same string!"; var_dump($another_string); # "deleting" a variable from memory unset($another_string); $string = 'string'; $parsed_string = "This is a $string"; var_dump($parsed_string); $parsed_string .= " with another {$string}"; var_dump($parsed_string); # with string parsing $heredoc = <<<HEREDOC This is the content of \$string: {$string} HEREDOC; var_dump($heredoc); # without string parsing (notice the single quotes surrounding NOWDOC) $nowdoc = <<<'NOWDOC' This is the content of \$string: {$string} NOWDOC; var_dump($nowdoc); # as of PHP5, defining an object typed stdClass => standard class $stdObject = new stdClass(); var_dump($stdObject); # defining an object typed Foo class Foo {} $foo = new Foo(); var_dump($foo); # defining an empty array $array = array(); var_dump($array); $assoc = array( 0 => $int, 'integer' => $int, 1 => $float, 'float' => $float, 2 => $string, 'string' => $string, 3 => NULL, // <=== key 3 is NULL 3, // <=== this is a value, not a key (key is 4) 5 => $stdObject, 'Foo' => $foo, ); var_dump($assoc); function a_function() { # not reachable var_dump(isset($foo)); // output: boolean false global $foo; # "global" (reachable) inside a_function()'s scope var_dump(isset($foo)); // output: boolean true } a_function();
Keep all operations the same but rewrite the snippet in PHP.
#macro assign(sym, expr) __fb_unquote__(__fb_eval__("#undef " + sym)) __fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr)))) #endmacro #define a, b, x assign("a", 8) assign("b", 7) assign("x", Sqr(a) + (Sin(b*3)/2)) Print x assign("x", "goodbye") Print x Sleep
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Port the following code from VB to PHP with equivalent syntax and logic.
#macro assign(sym, expr) __fb_unquote__(__fb_eval__("#undef " + sym)) __fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr)))) #endmacro #define a, b, x assign("a", 8) assign("b", 7) assign("x", Sqr(a) + (Sin(b*3)/2)) Print x assign("x", "goodbye") Print x Sleep
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Rewrite this program in C# while keeping its functionality equivalent to the Java version.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Change the programming language of this snippet from Java to C# without modifying what it does.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Write the same algorithm in C# as shown in this Java implementation.
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
using System; using System.Numerics; namespace PiCalc { internal class Program { private readonly BigInteger FOUR = new BigInteger(4); private readonly BigInteger SEVEN = new BigInteger(7); private readonly BigInteger TEN = new BigInteger(10); private readonly BigInteger THREE = new BigInteger(3); private readonly BigInteger TWO = new BigInteger(2); private BigInteger k = BigInteger.One; private BigInteger l = new BigInteger(3); private BigInteger n = new BigInteger(3); private BigInteger q = BigInteger.One; private BigInteger r = BigInteger.Zero; private BigInteger t = BigInteger.One; public void CalcPiDigits() { BigInteger nn, nr; bool first = true; while (true) { if ((FOUR*q + r - t).CompareTo(n*t) == -1) { Console.Write(n); if (first) { Console.Write("."); first = false; } nr = TEN*(r - (n*t)); n = TEN*(THREE*q + r)/t - (TEN*n); q *= TEN; r = nr; } else { nr = (TWO*q + r)*l; nn = (q*(SEVEN*k) + TWO + r*l)/(t*l); q *= k; t *= l; l += TWO; k += BigInteger.One; n = nn; r = nr; } } } private static void Main(string[] args) { new Program().CalcPiDigits(); } } }
Maintain the same structure and functionality when rewriting this code in C#.
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
using System; static class YCombinator<T, TResult> { private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r); public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x))); } static class Program { static void Main() { var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1)); var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2)); Console.WriteLine(fac(10)); Console.WriteLine(fib(10)); } }
Write a version of this Java function in C# with identical behavior.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
Convert this Java snippet to C# and keep its semantics consistent.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }