Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite the snippet below in PHP so it works the same as the original Go code. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| <?php
function s_of_n_creator($n) {
$sample = array();
$i = 0;
return function($item) use (&$sample, &$i, $n) {
$i++;
if ($i <= $n) {
$sample[] = $item;
} else if (rand(0, $i-1) < $n) {
$sample[rand(0, $n-1)] = $item;
}
return $sample;
};
}
$items = range(0, 9);
for ($trial = 0; $trial < 100000; $trial++) {
$s_of_n = s_of_n_creator(3);
foreach ($items as $item)
$sample = $s_of_n($item);
foreach ($sample as $s)
$bin[$s]++;
}
print_r($bin);
?>
|
Write the same code in PHP as shown below in Go. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| <?php
function s_of_n_creator($n) {
$sample = array();
$i = 0;
return function($item) use (&$sample, &$i, $n) {
$i++;
if ($i <= $n) {
$sample[] = $item;
} else if (rand(0, $i-1) < $n) {
$sample[rand(0, $n-1)] = $item;
}
return $sample;
};
}
$items = range(0, 9);
for ($trial = 0; $trial < 100000; $trial++) {
$s_of_n = s_of_n_creator(3);
foreach ($items as $item)
$sample = $s_of_n($item);
foreach ($sample as $s)
$bin[$s]++;
}
print_r($bin);
?>
|
Generate a PHP translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Transform the following Go implementation into PHP, maintaining the same output and logic. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Convert this Go snippet to PHP and keep its semantics consistent. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Port the following code from Go to PHP with equivalent syntax and logic. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Please provide an equivalent version of this Go code in PHP. | package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{7, 12, 60}
c := append(a, b...)
fmt.Println(c)
i := []interface{}{1, 2, 3}
j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
k := append(i, j...)
fmt.Println(k)
l := [...]int{1, 2, 3}
m := [...]int{7, 12, 60}
var n [len(l) + len(m)]int
copy(n[:], l[:])
copy(n[len(l):], m[:])
fmt.Println(n)
}
| $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
|
Rewrite this program in PHP while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{7, 12, 60}
c := append(a, b...)
fmt.Println(c)
i := []interface{}{1, 2, 3}
j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
k := append(i, j...)
fmt.Println(k)
l := [...]int{1, 2, 3}
m := [...]int{7, 12, 60}
var n [len(l) + len(m)]int
copy(n[:], l[:])
copy(n[len(l):], m[:])
fmt.Println(n)
}
| $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
|
Ensure the translated PHP code behaves exactly like the original Go snippet. | package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
}
| #!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);
|
Keep all operations the same but rewrite the snippet in PHP. | package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
}
| #!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);
|
Generate an equivalent PHP version of this Go code. | package main
import "fmt"
type item struct {
string
w, v int
}
var wants = []item{
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
}
const maxWt = 400
func main() {
items, w, v := m(len(wants)-1, maxWt)
fmt.Println(items)
fmt.Println("weight:", w)
fmt.Println("value:", v)
}
func m(i, w int) ([]string, int, int) {
if i < 0 || w == 0 {
return nil, 0, 0
} else if wants[i].w > w {
return m(i-1, w)
}
i0, w0, v0 := m(i-1, w)
i1, w1, v1 := m(i-1, w-wants[i].w)
v1 += wants[i].v
if v1 > v0 {
return append(i1, wants[i].string), w1 + wants[i].w, v1
}
return i0, w0, v0
}
| #########################################################
# 0-1 Knapsack Problem Solve with memoization optimize and index returns
# $w = weight of item
# $v = value of item
# $i = index
# $aW = Available Weight
# $m = Memo items array
# PHP Translation from Python, Memoization,
# and index return functionality added by Brian Berneker
#
#########################################################
function knapSolveFast2($w, $v, $i, $aW, &$m) {
global $numcalls;
$numcalls ++;
if (isset($m[$i][$aW])) {
return array( $m[$i][$aW], $m['picked'][$i][$aW] );
} else {
if ($i == 0) {
if ($w[$i] <= $aW) { // Will this item fit?
$m[$i][$aW] = $v[$i]; // Memo this item
$m['picked'][$i][$aW] = array($i); // and the picked item
return array($v[$i],array($i)); // Return the value of this item and add it to the picked list
} else {
$m[$i][$aW] = 0; // Memo zero
$m['picked'][$i][$aW] = array(); // and a blank array entry...
return array(0,array()); // Return nothing
}
}
list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);
if ($w[$i] > $aW) { // Does it return too many?
$m[$i][$aW] = $without_i; // Memo without including this one
$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...
return array($without_i, $without_PI); // and return it
} else {
list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);
$with_i += $v[$i]; // ..and add the value of this one..
if ($with_i > $without_i) {
$res = $with_i;
$picked = $with_PI;
array_push($picked,$i);
} else {
$res = $without_i;
$picked = $without_PI;
}
$m[$i][$aW] = $res; // Store it in the memo
$m['picked'][$i][$aW] = $picked; // and store the picked item
return array ($res,$picked); // and then return it
}
}
}
$items4 = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","t-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book");
$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);
$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);
## Initialize
$numcalls = 0; $m = array(); $pickedItems = array();
## Solve
list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);
# Display Result
echo "<b>Items:</b><br>".join(", ",$items4)."<br>";
echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>";
echo "<b>Array Indices:</b><br>".join(",",$pickedItems)."<br>";
echo "<b>Chosen Items:</b><br>";
echo "<table border cellspacing=0>";
echo "<tr><td>Item</td><td>Value</td><td>Weight</td></tr>";
$totalVal = $totalWt = 0;
foreach($pickedItems as $key) {
$totalVal += $v4[$key];
$totalWt += $w4[$key];
echo "<tr><td>".$items4[$key]."</td><td>".$v4[$key]."</td><td>".$w4[$key]."</td></tr>";
}
echo "<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>";
echo "</table><hr>";
|
Maintain the same structure and functionality when rewriting this code in PHP. | package main
import "fmt"
type item struct {
string
w, v int
}
var wants = []item{
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
}
const maxWt = 400
func main() {
items, w, v := m(len(wants)-1, maxWt)
fmt.Println(items)
fmt.Println("weight:", w)
fmt.Println("value:", v)
}
func m(i, w int) ([]string, int, int) {
if i < 0 || w == 0 {
return nil, 0, 0
} else if wants[i].w > w {
return m(i-1, w)
}
i0, w0, v0 := m(i-1, w)
i1, w1, v1 := m(i-1, w-wants[i].w)
v1 += wants[i].v
if v1 > v0 {
return append(i1, wants[i].string), w1 + wants[i].w, v1
}
return i0, w0, v0
}
| #########################################################
# 0-1 Knapsack Problem Solve with memoization optimize and index returns
# $w = weight of item
# $v = value of item
# $i = index
# $aW = Available Weight
# $m = Memo items array
# PHP Translation from Python, Memoization,
# and index return functionality added by Brian Berneker
#
#########################################################
function knapSolveFast2($w, $v, $i, $aW, &$m) {
global $numcalls;
$numcalls ++;
if (isset($m[$i][$aW])) {
return array( $m[$i][$aW], $m['picked'][$i][$aW] );
} else {
if ($i == 0) {
if ($w[$i] <= $aW) { // Will this item fit?
$m[$i][$aW] = $v[$i]; // Memo this item
$m['picked'][$i][$aW] = array($i); // and the picked item
return array($v[$i],array($i)); // Return the value of this item and add it to the picked list
} else {
$m[$i][$aW] = 0; // Memo zero
$m['picked'][$i][$aW] = array(); // and a blank array entry...
return array(0,array()); // Return nothing
}
}
list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);
if ($w[$i] > $aW) { // Does it return too many?
$m[$i][$aW] = $without_i; // Memo without including this one
$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...
return array($without_i, $without_PI); // and return it
} else {
list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);
$with_i += $v[$i]; // ..and add the value of this one..
if ($with_i > $without_i) {
$res = $with_i;
$picked = $with_PI;
array_push($picked,$i);
} else {
$res = $without_i;
$picked = $without_PI;
}
$m[$i][$aW] = $res; // Store it in the memo
$m['picked'][$i][$aW] = $picked; // and store the picked item
return array ($res,$picked); // and then return it
}
}
}
$items4 = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","t-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book");
$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);
$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);
## Initialize
$numcalls = 0; $m = array(); $pickedItems = array();
## Solve
list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);
# Display Result
echo "<b>Items:</b><br>".join(", ",$items4)."<br>";
echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>";
echo "<b>Array Indices:</b><br>".join(",",$pickedItems)."<br>";
echo "<b>Chosen Items:</b><br>";
echo "<table border cellspacing=0>";
echo "<tr><td>Item</td><td>Value</td><td>Weight</td></tr>";
$totalVal = $totalWt = 0;
foreach($pickedItems as $key) {
$totalVal += $v4[$key];
$totalWt += $w4[$key];
echo "<tr><td>".$items4[$key]."</td><td>".$v4[$key]."</td><td>".$w4[$key]."</td></tr>";
}
echo "<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>";
echo "</table><hr>";
|
Convert this Go block to PHP, preserving its control flow and logic. | package main
import "math"
import "fmt"
func cube(x float64) float64 { return math.Pow(x, 3) }
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
funclist := []ffType{math.Sin, math.Cos, cube}
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}
| $compose = function ($f, $g) {
return function ($x) use ($f, $g) {
return $f($g($x));
};
};
$fn = array('sin', 'cos', function ($x) { return pow($x, 3); });
$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });
for ($i = 0; $i < 3; $i++) {
$f = $compose($inv[$i], $fn[$i]);
echo $f(0.5), PHP_EOL;
}
|
Translate this program into PHP but keep the logic exactly as in Go. | package main
import "math"
import "fmt"
func cube(x float64) float64 { return math.Pow(x, 3) }
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
funclist := []ffType{math.Sin, math.Cos, cube}
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}
| $compose = function ($f, $g) {
return function ($x) use ($f, $g) {
return $f($g($x));
};
};
$fn = array('sin', 'cos', function ($x) { return pow($x, 3); });
$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });
for ($i = 0; $i < 3; $i++) {
$f = $compose($inv[$i], $fn[$i]);
echo $f(0.5), PHP_EOL;
}
|
Transform the following Go implementation into PHP, maintaining the same output and logic. | package main
import (
"fmt"
"strconv"
)
func listProperDivisors(limit int) {
if limit < 1 {
return
}
width := len(strconv.Itoa(limit))
for i := 1; i <= limit; i++ {
fmt.Printf("%*d -> ", width, i)
if i == 1 {
fmt.Println("(None)")
continue
}
for j := 1; j <= i/2; j++ {
if i%j == 0 {
fmt.Printf(" %d", j)
}
}
fmt.Println()
}
}
func countProperDivisors(n int) int {
if n < 2 {
return 0
}
count := 0
for i := 1; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
fmt.Println()
maxCount := 0
most := []int{1}
for n := 2; n <= 20000; n++ {
count := countProperDivisors(n)
if count == maxCount {
most = append(most, n)
} else if count > maxCount {
maxCount = count
most = most[0:1]
most[0] = n
}
}
fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
fmt.Println("namely", maxCount, "\b\n")
for _, n := range most {
fmt.Println(n)
}
}
| <?php
function ProperDivisors($n) {
yield 1;
$large_divisors = [];
for ($i = 2; $i <= sqrt($n); $i++) {
if ($n % $i == 0) {
yield $i;
if ($i*$i != $n) {
$large_divisors[] = $n / $i;
}
}
}
foreach (array_reverse($large_divisors) as $i) {
yield $i;
}
}
assert([1, 2, 4, 5, 10, 20, 25, 50] ==
iterator_to_array(ProperDivisors(100)));
foreach (range(1, 10) as $n) {
echo "$n =>";
foreach (ProperDivisors($n) as $divisor) {
echo " $divisor";
}
echo "\n";
}
$divisorsCount = [];
for ($i = 1; $i < 20000; $i++) {
$divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;
}
ksort($divisorsCount);
echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n";
echo "They have ", key($divisorsCount), " divisors.\n";
|
Generate a PHP translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"strconv"
)
func listProperDivisors(limit int) {
if limit < 1 {
return
}
width := len(strconv.Itoa(limit))
for i := 1; i <= limit; i++ {
fmt.Printf("%*d -> ", width, i)
if i == 1 {
fmt.Println("(None)")
continue
}
for j := 1; j <= i/2; j++ {
if i%j == 0 {
fmt.Printf(" %d", j)
}
}
fmt.Println()
}
}
func countProperDivisors(n int) int {
if n < 2 {
return 0
}
count := 0
for i := 1; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
fmt.Println()
maxCount := 0
most := []int{1}
for n := 2; n <= 20000; n++ {
count := countProperDivisors(n)
if count == maxCount {
most = append(most, n)
} else if count > maxCount {
maxCount = count
most = most[0:1]
most[0] = n
}
}
fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
fmt.Println("namely", maxCount, "\b\n")
for _, n := range most {
fmt.Println(n)
}
}
| <?php
function ProperDivisors($n) {
yield 1;
$large_divisors = [];
for ($i = 2; $i <= sqrt($n); $i++) {
if ($n % $i == 0) {
yield $i;
if ($i*$i != $n) {
$large_divisors[] = $n / $i;
}
}
}
foreach (array_reverse($large_divisors) as $i) {
yield $i;
}
}
assert([1, 2, 4, 5, 10, 20, 25, 50] ==
iterator_to_array(ProperDivisors(100)));
foreach (range(1, 10) as $n) {
echo "$n =>";
foreach (ProperDivisors($n) as $divisor) {
echo " $divisor";
}
echo "\n";
}
$divisorsCount = [];
for ($i = 1; $i < 20000; $i++) {
$divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;
}
ksort($divisorsCount);
echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n";
echo "They have ", key($divisorsCount), " divisors.\n";
|
Transform the following Go implementation into PHP, maintaining the same output and logic. | package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
}
| $string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
|
Write a version of this Go function in PHP with identical behavior. | package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
}
| $string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
|
Write the same algorithm in PHP as shown in this Go implementation. | package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}
| $keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);
|
Maintain the same structure and functionality when rewriting this code in PHP. | package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}
| $keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);
|
Convert this Go block to PHP, preserving its control flow and logic. | package main
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
x2 := x + distance*math.Sin(direction*math.Pi/180)
y2 := y - distance*math.Cos(direction*math.Pi/180)
g.AaLine(x, y, x2, y2)
if depth > 0 {
ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
}
}
| <?php
header("Content-type: image/png");
$width = 512;
$height = 512;
$img = imagecreatetruecolor($width,$height);
$bg = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img, 0, 0, $width, $width, $bg);
$depth = 8;
function drawTree($x1, $y1, $angle, $depth){
global $img;
if ($depth != 0){
$x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);
$y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);
imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));
drawTree($x2, $y2, $angle - 20, $depth - 1);
drawTree($x2, $y2, $angle + 20, $depth - 1);
}
}
drawTree($width/2, $height, -90, $depth);
imagepng($img);
imagedestroy($img);
?>
|
Write the same algorithm in PHP as shown in this Go implementation. | package main
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
x2 := x + distance*math.Sin(direction*math.Pi/180)
y2 := y - distance*math.Cos(direction*math.Pi/180)
g.AaLine(x, y, x2, y2)
if depth > 0 {
ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
}
}
| <?php
header("Content-type: image/png");
$width = 512;
$height = 512;
$img = imagecreatetruecolor($width,$height);
$bg = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img, 0, 0, $width, $width, $bg);
$depth = 8;
function drawTree($x1, $y1, $angle, $depth){
global $img;
if ($depth != 0){
$x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);
$y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);
imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));
drawTree($x2, $y2, $angle - 20, $depth - 1);
drawTree($x2, $y2, $angle + 20, $depth - 1);
}
}
drawTree($width/2, $height, -90, $depth);
imagepng($img);
imagedestroy($img);
?>
|
Translate the given Go code snippet into PHP without altering its behavior. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| <?php
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
|
Keep all operations the same but rewrite the snippet in PHP. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| <?php
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
|
Translate this program into PHP but keep the logic exactly as in Go. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| <?php
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
|
Write a version of this Go function in PHP with identical behavior. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| <?php
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
|
Rewrite the snippet below in PHP so it works the same as the original Go code. | package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Five Rank = 5
Six Rank = 6
Seven Rank = 7
Eight Rank = 8
Nine Rank = 9
Ten Rank = 10
Jack Rank = 11
Queen Rank = 12
King Rank = 13
)
func (r Rank) String() string {
const ranks = "A23456789TJQK"
return ranks[r-1 : r]
}
type Card uint8
func NewCard(r Rank, s Suit) Card {
return Card(13*uint8(s) + uint8(r-1))
}
func (c Card) RankSuit() (Rank, Suit) {
return Rank(c%13 + 1), Suit(c / 13)
}
func (c Card) Rank() Rank {
return Rank(c%13 + 1)
}
func (c Card) Suit() Suit {
return Suit(c / 13)
}
func (c Card) String() string {
return c.Rank().String() + c.Suit().String()
}
type Deck []Card
func NewDeck() Deck {
d := make(Deck, 52)
for i := range d {
d[i] = Card(i)
}
return d
}
func (d Deck) String() string {
s := ""
for i, c := range d {
switch {
case i == 0:
case i%13 == 0:
s += "\n"
default:
s += " "
}
s += c.String()
}
return s
}
func (d Deck) Shuffle() {
for i := range d {
j := rand.Intn(i + 1)
d[i], d[j] = d[j], d[i]
}
}
func (d Deck) Contains(tc Card) bool {
for _, c := range d {
if c == tc {
return true
}
}
return false
}
func (d *Deck) AddDeck(decks ...Deck) {
for _, o := range decks {
*d = append(*d, o...)
}
}
func (d *Deck) AddCard(c Card) {
*d = append(*d, c)
}
func (d *Deck) Draw(n int) Deck {
old := *d
*d = old[n:]
return old[:n:n]
}
func (d *Deck) DrawCard() (Card, bool) {
if len(*d) == 0 {
return 0, false
}
old := *d
*d = old[1:]
return old[0], true
}
func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {
for i := 0; i < cards; i++ {
for j := range hands {
if len(*d) == 0 {
return hands, false
}
hands[j] = append(hands[j], (*d)[0])
*d = (*d)[1:]
}
}
return hands, true
}
| class Card
{
protected static $suits = array( '♠', '♥', '♦', '♣' );
protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );
protected $suit;
protected $suitOrder;
protected $pip;
protected $pipOrder;
protected $order;
public function __construct( $suit, $pip )
{
if( !in_array( $suit, self::$suits ) )
{
throw new InvalidArgumentException( 'Invalid suit' );
}
if( !in_array( $pip, self::$pips ) )
{
throw new InvalidArgumentException( 'Invalid pip' );
}
$this->suit = $suit;
$this->pip = $pip;
}
public function getSuit()
{
return $this->suit;
}
public function getPip()
{
return $this->pip;
}
public function getSuitOrder()
{
if( !isset( $this->suitOrder ) )
{
$this->suitOrder = array_search( $this->suit, self::$suits );
}
return $this->suitOrder;
}
public function getPipOrder()
{
if( !isset( $this->pipOrder ) )
{
$this->pipOrder = array_search( $this->pip, self::$pips );
}
return $this->pipOrder;
}
public function getOrder()
{
if( !isset( $this->order ) )
{
$suitOrder = $this->getSuitOrder();
$pipOrder = $this->getPipOrder();
$this->order = $pipOrder * count( self::$suits ) + $suitOrder;
}
return $this->order;
}
public function compareSuit( Card $other )
{
return $this->getSuitOrder() - $other->getSuitOrder();
}
public function comparePip( Card $other )
{
return $this->getPipOrder() - $other->getPipOrder();
}
public function compare( Card $other )
{
return $this->getOrder() - $other->getOrder();
}
public function __toString()
{
return $this->suit . $this->pip;
}
public static function getSuits()
{
return self::$suits;
}
public static function getPips()
{
return self::$pips;
}
}
class CardCollection
implements Countable, Iterator
{
protected $cards = array();
protected function __construct( array $cards = array() )
{
foreach( $cards as $card )
{
$this->addCard( $card );
}
}
public function count()
{
return count( $this->cards );
}
public function key()
{
return key( $this->cards );
}
public function valid()
{
return null !== $this->key();
}
public function next()
{
next( $this->cards );
}
public function current()
{
return current( $this->cards );
}
public function rewind()
{
reset( $this->cards );
}
public function sort( $comparer = null )
{
$comparer = $comparer ?: function( $a, $b ) {
return $a->compare( $b );
};
if( !is_callable( $comparer ) )
{
throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );
}
usort( $this->cards, $comparer );
return $this;
}
public function toString()
{
return implode( ' ', $this->cards );
}
public function __toString()
{
return $this->toString();
}
protected function addCard( Card $card )
{
if( in_array( $card, $this->cards ) )
{
throw new DomainException( 'Card is already present in this collection' );
}
$this->cards[] = $card;
}
}
class Deck
extends CardCollection
{
public function __construct( $shuffled = false )
{
foreach( Card::getSuits() as $suit )
{
foreach( Card::getPips() as $pip )
{
$this->addCard( new Card( $suit, $pip ) );
}
}
if( $shuffled )
{
$this->shuffle();
}
}
public function deal( $amount = 1, CardCollection $cardCollection = null )
{
if( !is_int( $amount ) || $amount < 1 )
{
throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );
}
if( $amount > count( $this->cards ) )
{
throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );
}
$cards = array_splice( $this->cards, 0, $amount );
$cardCollection = $cardCollection ?: new CardCollection;
foreach( $cards as $card )
{
$cardCollection->addCard( $card );
}
return $cardCollection;
}
public function shuffle()
{
shuffle( $this->cards );
}
}
class Hand
extends CardCollection
{
public function __construct() {}
public function play( $position )
{
if( !isset( $this->cards[ $position ] ) )
{
throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );
}
$result = array_splice( $this->cards, $position, 1 );
return $result[ 0 ];
}
}
|
Keep all operations the same but rewrite the snippet in PHP. | package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Five Rank = 5
Six Rank = 6
Seven Rank = 7
Eight Rank = 8
Nine Rank = 9
Ten Rank = 10
Jack Rank = 11
Queen Rank = 12
King Rank = 13
)
func (r Rank) String() string {
const ranks = "A23456789TJQK"
return ranks[r-1 : r]
}
type Card uint8
func NewCard(r Rank, s Suit) Card {
return Card(13*uint8(s) + uint8(r-1))
}
func (c Card) RankSuit() (Rank, Suit) {
return Rank(c%13 + 1), Suit(c / 13)
}
func (c Card) Rank() Rank {
return Rank(c%13 + 1)
}
func (c Card) Suit() Suit {
return Suit(c / 13)
}
func (c Card) String() string {
return c.Rank().String() + c.Suit().String()
}
type Deck []Card
func NewDeck() Deck {
d := make(Deck, 52)
for i := range d {
d[i] = Card(i)
}
return d
}
func (d Deck) String() string {
s := ""
for i, c := range d {
switch {
case i == 0:
case i%13 == 0:
s += "\n"
default:
s += " "
}
s += c.String()
}
return s
}
func (d Deck) Shuffle() {
for i := range d {
j := rand.Intn(i + 1)
d[i], d[j] = d[j], d[i]
}
}
func (d Deck) Contains(tc Card) bool {
for _, c := range d {
if c == tc {
return true
}
}
return false
}
func (d *Deck) AddDeck(decks ...Deck) {
for _, o := range decks {
*d = append(*d, o...)
}
}
func (d *Deck) AddCard(c Card) {
*d = append(*d, c)
}
func (d *Deck) Draw(n int) Deck {
old := *d
*d = old[n:]
return old[:n:n]
}
func (d *Deck) DrawCard() (Card, bool) {
if len(*d) == 0 {
return 0, false
}
old := *d
*d = old[1:]
return old[0], true
}
func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {
for i := 0; i < cards; i++ {
for j := range hands {
if len(*d) == 0 {
return hands, false
}
hands[j] = append(hands[j], (*d)[0])
*d = (*d)[1:]
}
}
return hands, true
}
| class Card
{
protected static $suits = array( '♠', '♥', '♦', '♣' );
protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );
protected $suit;
protected $suitOrder;
protected $pip;
protected $pipOrder;
protected $order;
public function __construct( $suit, $pip )
{
if( !in_array( $suit, self::$suits ) )
{
throw new InvalidArgumentException( 'Invalid suit' );
}
if( !in_array( $pip, self::$pips ) )
{
throw new InvalidArgumentException( 'Invalid pip' );
}
$this->suit = $suit;
$this->pip = $pip;
}
public function getSuit()
{
return $this->suit;
}
public function getPip()
{
return $this->pip;
}
public function getSuitOrder()
{
if( !isset( $this->suitOrder ) )
{
$this->suitOrder = array_search( $this->suit, self::$suits );
}
return $this->suitOrder;
}
public function getPipOrder()
{
if( !isset( $this->pipOrder ) )
{
$this->pipOrder = array_search( $this->pip, self::$pips );
}
return $this->pipOrder;
}
public function getOrder()
{
if( !isset( $this->order ) )
{
$suitOrder = $this->getSuitOrder();
$pipOrder = $this->getPipOrder();
$this->order = $pipOrder * count( self::$suits ) + $suitOrder;
}
return $this->order;
}
public function compareSuit( Card $other )
{
return $this->getSuitOrder() - $other->getSuitOrder();
}
public function comparePip( Card $other )
{
return $this->getPipOrder() - $other->getPipOrder();
}
public function compare( Card $other )
{
return $this->getOrder() - $other->getOrder();
}
public function __toString()
{
return $this->suit . $this->pip;
}
public static function getSuits()
{
return self::$suits;
}
public static function getPips()
{
return self::$pips;
}
}
class CardCollection
implements Countable, Iterator
{
protected $cards = array();
protected function __construct( array $cards = array() )
{
foreach( $cards as $card )
{
$this->addCard( $card );
}
}
public function count()
{
return count( $this->cards );
}
public function key()
{
return key( $this->cards );
}
public function valid()
{
return null !== $this->key();
}
public function next()
{
next( $this->cards );
}
public function current()
{
return current( $this->cards );
}
public function rewind()
{
reset( $this->cards );
}
public function sort( $comparer = null )
{
$comparer = $comparer ?: function( $a, $b ) {
return $a->compare( $b );
};
if( !is_callable( $comparer ) )
{
throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );
}
usort( $this->cards, $comparer );
return $this;
}
public function toString()
{
return implode( ' ', $this->cards );
}
public function __toString()
{
return $this->toString();
}
protected function addCard( Card $card )
{
if( in_array( $card, $this->cards ) )
{
throw new DomainException( 'Card is already present in this collection' );
}
$this->cards[] = $card;
}
}
class Deck
extends CardCollection
{
public function __construct( $shuffled = false )
{
foreach( Card::getSuits() as $suit )
{
foreach( Card::getPips() as $pip )
{
$this->addCard( new Card( $suit, $pip ) );
}
}
if( $shuffled )
{
$this->shuffle();
}
}
public function deal( $amount = 1, CardCollection $cardCollection = null )
{
if( !is_int( $amount ) || $amount < 1 )
{
throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );
}
if( $amount > count( $this->cards ) )
{
throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );
}
$cards = array_splice( $this->cards, 0, $amount );
$cardCollection = $cardCollection ?: new CardCollection;
foreach( $cards as $card )
{
$cardCollection->addCard( $card );
}
return $cardCollection;
}
public function shuffle()
{
shuffle( $this->cards );
}
}
class Hand
extends CardCollection
{
public function __construct() {}
public function play( $position )
{
if( !isset( $this->cards[ $position ] ) )
{
throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );
}
$result = array_splice( $this->cards, $position, 1 );
return $result[ 0 ];
}
}
|
Convert the following code from Go to PHP, ensuring the logic remains intact. | package main
import (
"fmt"
)
func main() {
var a [5]int
fmt.Println("len(a) =", len(a))
fmt.Println("a =", a)
a[0] = 3
fmt.Println("a =", a)
fmt.Println("a[0] =", a[0])
s := a[:4]
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
s = s[:5]
fmt.Println("s =", s)
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
}
| $NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];
|
Convert this Go block to PHP, preserving its control flow and logic. | package main
import (
"fmt"
)
func main() {
var a [5]int
fmt.Println("len(a) =", len(a))
fmt.Println("a =", a)
a[0] = 3
fmt.Println("a =", a)
fmt.Println("a[0] =", a[0])
s := a[:4]
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
s = s[:5]
fmt.Println("s =", s)
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
}
| $NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];
|
Convert this Go block to PHP, preserving its control flow and logic. | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
}
| <?php
function isSierpinskiCarpetPixelFilled($x, $y) {
while (($x > 0) or ($y > 0)) {
if (($x % 3 == 1) and ($y % 3 == 1)) {
return false;
}
$x /= 3;
$y /= 3;
}
return true;
}
function sierpinskiCarpet($order) {
$size = pow(3, $order);
for ($y = 0 ; $y < $size ; $y++) {
for ($x = 0 ; $x < $size ; $x++) {
echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';
}
echo PHP_EOL;
}
}
for ($order = 0 ; $order <= 3 ; $order++) {
echo 'N=', $order, PHP_EOL;
sierpinskiCarpet($order);
echo PHP_EOL;
}
|
Preserve the algorithm and functionality while converting the code from Go to PHP. | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
}
| <?php
function isSierpinskiCarpetPixelFilled($x, $y) {
while (($x > 0) or ($y > 0)) {
if (($x % 3 == 1) and ($y % 3 == 1)) {
return false;
}
$x /= 3;
$y /= 3;
}
return true;
}
function sierpinskiCarpet($order) {
$size = pow(3, $order);
for ($y = 0 ; $y < $size ; $y++) {
for ($x = 0 ; $x < $size ; $x++) {
echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';
}
echo PHP_EOL;
}
}
for ($order = 0 ; $order <= 3 ; $order++) {
echo 'N=', $order, PHP_EOL;
sierpinskiCarpet($order);
echo PHP_EOL;
}
|
Change the following Go code into PHP without altering its purpose. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
rand.Seed(time.Now().UnixNano())
fmt.Println("unsorted:", list)
temp := make([]int, len(list))
copy(temp, list)
for !sort.IntsAreSorted(temp) {
for i, v := range rand.Perm(len(list)) {
temp[i] = list[v]
}
}
fmt.Println("sorted! ", temp)
}
| function bogosort($l) {
while (!in_order($l))
shuffle($l);
return $l;
}
function in_order($l) {
for ($i = 1; $i < count($l); $i++)
if ($l[$i] < $l[$i-1])
return FALSE;
return TRUE;
}
|
Preserve the algorithm and functionality while converting the code from Go to PHP. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
rand.Seed(time.Now().UnixNano())
fmt.Println("unsorted:", list)
temp := make([]int, len(list))
copy(temp, list)
for !sort.IntsAreSorted(temp) {
for i, v := range rand.Perm(len(list)) {
temp[i] = list[v]
}
}
fmt.Println("sorted! ", temp)
}
| function bogosort($l) {
while (!in_order($l))
shuffle($l);
return $l;
}
function in_order($l) {
for ($i = 1; $i < count($l); $i++)
if ($l[$i] < $l[$i-1])
return FALSE;
return TRUE;
}
|
Generate a PHP translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
| <?php
for($i=1;$i<=22;$i++){
echo($i + floor(1/2 + sqrt($i)) . "\n");
}
$found_square=False;
for($i=1;$i<=1000000;$i++){
$non_square=$i + floor(1/2 + sqrt($i));
if(sqrt($non_square)==intval(sqrt($non_square))){
$found_square=True;
}
}
echo("\n");
if($found_square){
echo("Found a square number, so the formula does not always work.");
} else {
echo("Up to 1000000, found no square number in the sequence!");
}
?>
|
Convert the following code from Go to PHP, ensuring the logic remains intact. | package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
| <?php
for($i=1;$i<=22;$i++){
echo($i + floor(1/2 + sqrt($i)) . "\n");
}
$found_square=False;
for($i=1;$i<=1000000;$i++){
$non_square=$i + floor(1/2 + sqrt($i));
if(sqrt($non_square)==intval(sqrt($non_square))){
$found_square=True;
}
}
echo("\n");
if($found_square){
echo("Found a square number, so the formula does not always work.");
} else {
echo("Up to 1000000, found no square number in the sequence!");
}
?>
|
Produce a language-to-language conversion: from Go to PHP, same semantics. | package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
| <?php
$str = 'abcdefgh';
$n = 2;
$m = 3;
echo substr($str, $n, $m), "\n"; //cde
echo substr($str, $n), "\n"; //cdefgh
echo substr($str, 0, -1), "\n"; //abcdefg
echo substr($str, strpos($str, 'd'), $m), "\n"; //def
echo substr($str, strpos($str, 'de'), $m), "\n"; //def
?>
|
Translate this program into PHP but keep the logic exactly as in Go. | package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
| <?php
$str = 'abcdefgh';
$n = 2;
$m = 3;
echo substr($str, $n, $m), "\n"; //cde
echo substr($str, $n), "\n"; //cdefgh
echo substr($str, 0, -1), "\n"; //abcdefg
echo substr($str, strpos($str, 'd'), $m), "\n"; //def
echo substr($str, strpos($str, 'de'), $m), "\n"; //def
?>
|
Keep all operations the same but rewrite the snippet in PHP. | func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
}
| <?php
function isLeapYear($year) {
if ($year % 100 == 0) {
return ($year % 400 == 0);
}
return ($year % 4 == 0);
}
|
Rewrite this program in PHP while keeping its functionality equivalent to the Go version. | func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
}
| <?php
function isLeapYear($year) {
if ($year % 100 == 0) {
return ($year % 400 == 0);
}
return ($year % 4 == 0);
}
|
Ensure the translated PHP code behaves exactly like the original Go snippet. | package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
| $orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');
$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');
$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');
function NumberToEnglish($num, $count = 0){
global $orderOfMag, $smallNumbers, $decades;
$isLast = true;
$str = '';
if ($num < 0){
$str = 'Negative ';
$num = abs($num);
}
(int) $thisPart = substr((string) $num, -3);
if (strlen((string) $num) > 3){
$str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);
$isLast = false;
}
if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))
$and = '';
else
$and = ' and ';
if ($thisPart > 99){
$str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}";
if(($thisPart %= 100) == 0){
$str .= " {$orderOfMag[$count]}";
return $str;
}
$and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk
}
if ($thisPart >= 20){
$str .= "{$and}{$decades[$thisPart /10]}";
$and = ' '; // Make sure we don't have any extranious "and"s
if(($thisPart %= 10) == 0)
return $str . ($count != 0 ? " {$orderOfMag[$count]}" : '');
}
if ($thisPart < 20 && $thisPart > 0)
return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : '');
elseif ($thisPart == 0 && strlen($thisPart) == 1)
return $str . "{$smallNumbers[(int)$thisPart]}";
}
|
Keep all operations the same but rewrite the snippet in PHP. | package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
| $orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');
$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');
$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');
function NumberToEnglish($num, $count = 0){
global $orderOfMag, $smallNumbers, $decades;
$isLast = true;
$str = '';
if ($num < 0){
$str = 'Negative ';
$num = abs($num);
}
(int) $thisPart = substr((string) $num, -3);
if (strlen((string) $num) > 3){
$str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);
$isLast = false;
}
if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))
$and = '';
else
$and = ' and ';
if ($thisPart > 99){
$str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}";
if(($thisPart %= 100) == 0){
$str .= " {$orderOfMag[$count]}";
return $str;
}
$and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk
}
if ($thisPart >= 20){
$str .= "{$and}{$decades[$thisPart /10]}";
$and = ' '; // Make sure we don't have any extranious "and"s
if(($thisPart %= 10) == 0)
return $str . ($count != 0 ? " {$orderOfMag[$count]}" : '');
}
if ($thisPart < 20 && $thisPart > 0)
return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : '');
elseif ($thisPart == 0 && strlen($thisPart) == 1)
return $str . "{$smallNumbers[(int)$thisPart]}";
}
|
Write the same algorithm in PHP as shown in this Go implementation. | package main
import (
"fmt"
"os"
"sort"
)
func main() {
if len(os.Args) == 1 {
compareStrings("abcd", "123456789", "abcdef", "1234567")
} else {
strings := os.Args[1:]
compareStrings(strings...)
}
}
func compareStrings(strings ...string) {
sort.SliceStable(strings, func(i, j int) bool {
return len(strings[i]) > len(strings[j])
})
for _, s := range strings {
fmt.Printf("%d: %s\n", len(s), s)
}
}
| <?php
function retrieveStrings()
{
if (isset($_POST['input'])) {
$strings = explode("\n", $_POST['input']);
} else {
$strings = ['abcd', '123456789', 'abcdef', '1234567'];
}
return $strings;
}
function setInput()
{
echo join("\n", retrieveStrings());
}
function setOutput()
{
$strings = retrieveStrings();
$strings = array_map('trim', $strings);
$strings = array_filter($strings);
if (!empty($strings)) {
usort($strings, function ($a, $b) {
return strlen($b) - strlen($a);
});
$max_len = strlen($strings[0]);
$min_len = strlen($strings[count($strings) - 1]);
foreach ($strings as $s) {
$length = strlen($s);
if ($length == $max_len) {
$predicate = "is the longest string";
} elseif ($length == $min_len) {
$predicate = "is the shortest string";
} else {
$predicate = "is neither the longest nor the shortest string";
}
echo "$s has length $length and $predicate\n";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
margin-top: 4ch;
margin-bottom: 4ch;
}
label {
display: block;
margin-bottom: 1ch;
}
textarea {
display: block;
}
input {
display: block;
margin-top: 4ch;
margin-bottom: 4ch;
}
</style>
</head>
<body>
<main>
<form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8">
<div>
<label for="input">Input:
</label>
<textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>
</label>
</div>
<input type="submit" value="press to compare strings">
</input>
<div>
<label for="Output">Output:
</label>
<textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>
</div>
</form>
</main>
</body>
</html>
|
Keep all operations the same but rewrite the snippet in PHP. | package main
import (
"fmt"
"os"
"sort"
)
func main() {
if len(os.Args) == 1 {
compareStrings("abcd", "123456789", "abcdef", "1234567")
} else {
strings := os.Args[1:]
compareStrings(strings...)
}
}
func compareStrings(strings ...string) {
sort.SliceStable(strings, func(i, j int) bool {
return len(strings[i]) > len(strings[j])
})
for _, s := range strings {
fmt.Printf("%d: %s\n", len(s), s)
}
}
| <?php
function retrieveStrings()
{
if (isset($_POST['input'])) {
$strings = explode("\n", $_POST['input']);
} else {
$strings = ['abcd', '123456789', 'abcdef', '1234567'];
}
return $strings;
}
function setInput()
{
echo join("\n", retrieveStrings());
}
function setOutput()
{
$strings = retrieveStrings();
$strings = array_map('trim', $strings);
$strings = array_filter($strings);
if (!empty($strings)) {
usort($strings, function ($a, $b) {
return strlen($b) - strlen($a);
});
$max_len = strlen($strings[0]);
$min_len = strlen($strings[count($strings) - 1]);
foreach ($strings as $s) {
$length = strlen($s);
if ($length == $max_len) {
$predicate = "is the longest string";
} elseif ($length == $min_len) {
$predicate = "is the shortest string";
} else {
$predicate = "is neither the longest nor the shortest string";
}
echo "$s has length $length and $predicate\n";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
margin-top: 4ch;
margin-bottom: 4ch;
}
label {
display: block;
margin-bottom: 1ch;
}
textarea {
display: block;
}
input {
display: block;
margin-top: 4ch;
margin-bottom: 4ch;
}
</style>
</head>
<body>
<main>
<form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8">
<div>
<label for="input">Input:
</label>
<textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>
</label>
</div>
<input type="submit" value="press to compare strings">
</input>
<div>
<label for="Output">Output:
</label>
<textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>
</div>
</form>
</main>
</body>
</html>
|
Preserve the algorithm and functionality while converting the code from Go to PHP. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {
for i := inc; i < len(a); i++ {
j, temp := i, a[i]
for ; j >= inc && a[j-inc] > temp; j -= inc {
a[j] = a[j-inc]
}
a[j] = temp
}
}
fmt.Println("after: ", a)
}
| function shellSort($arr)
{
$inc = round(count($arr)/2);
while($inc > 0)
{
for($i = $inc; $i < count($arr);$i++){
$temp = $arr[$i];
$j = $i;
while($j >= $inc && $arr[$j-$inc] > $temp)
{
$arr[$j] = $arr[$j - $inc];
$j -= $inc;
}
$arr[$j] = $temp;
}
$inc = round($inc/2.2);
}
return $arr;
}
|
Produce a functionally identical PHP code for the snippet given in Go. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {
for i := inc; i < len(a); i++ {
j, temp := i, a[i]
for ; j >= inc && a[j-inc] > temp; j -= inc {
a[j] = a[j-inc]
}
a[j] = temp
}
}
fmt.Println("after: ", a)
}
| function shellSort($arr)
{
$inc = round(count($arr)/2);
while($inc > 0)
{
for($i = $inc; $i < count($arr);$i++){
$temp = $arr[$i];
$j = $i;
while($j >= $inc && $arr[$j-$inc] > $temp)
{
$arr[$j] = $arr[$j - $inc];
$j -= $inc;
}
$arr[$j] = $temp;
}
$inc = round($inc/2.2);
}
return $arr;
}
|
Keep all operations the same but rewrite the snippet in PHP. | package main
import (
"fmt"
"io/ioutil"
"sort"
"unicode"
)
const file = "unixdict.txt"
func main() {
bs, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return
}
m := make(map[rune]int)
for _, r := range string(bs) {
m[r]++
}
lfs := make(lfList, 0, len(m))
for l, f := range m {
lfs = append(lfs, &letterFreq{l, f})
}
sort.Sort(lfs)
fmt.Println("file:", file)
fmt.Println("letter frequency")
for _, lf := range lfs {
if unicode.IsGraphic(lf.rune) {
fmt.Printf(" %c %7d\n", lf.rune, lf.freq)
} else {
fmt.Printf("%U %7d\n", lf.rune, lf.freq)
}
}
}
type letterFreq struct {
rune
freq int
}
type lfList []*letterFreq
func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
switch fd := lfs[i].freq - lfs[j].freq; {
case fd < 0:
return false
case fd > 0:
return true
}
return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
lfs[i], lfs[j] = lfs[j], lfs[i]
}
| <?php
print_r(array_count_values(str_split(file_get_contents($argv[1]))));
?>
|
Convert the following code from Go to PHP, ensuring the logic remains intact. | package main
import (
"fmt"
"io/ioutil"
"sort"
"unicode"
)
const file = "unixdict.txt"
func main() {
bs, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return
}
m := make(map[rune]int)
for _, r := range string(bs) {
m[r]++
}
lfs := make(lfList, 0, len(m))
for l, f := range m {
lfs = append(lfs, &letterFreq{l, f})
}
sort.Sort(lfs)
fmt.Println("file:", file)
fmt.Println("letter frequency")
for _, lf := range lfs {
if unicode.IsGraphic(lf.rune) {
fmt.Printf(" %c %7d\n", lf.rune, lf.freq)
} else {
fmt.Printf("%U %7d\n", lf.rune, lf.freq)
}
}
}
type letterFreq struct {
rune
freq int
}
type lfList []*letterFreq
func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
switch fd := lfs[i].freq - lfs[j].freq; {
case fd < 0:
return false
case fd > 0:
return true
}
return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
lfs[i], lfs[j] = lfs[j], lfs[i]
}
| <?php
print_r(array_count_values(str_split(file_get_contents($argv[1]))));
?>
|
Transform the following Go implementation into PHP, maintaining the same output and logic. | package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}
| $s = "12345";
$s++;
|
Transform the following Go implementation into PHP, maintaining the same output and logic. | package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}
| $s = "12345";
$s++;
|
Port the following code from Go to PHP with equivalent syntax and logic. | package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}
| <?php
function stripchars($s, $chars) {
return str_replace(str_split($chars), "", $s);
}
echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
?>
|
Keep all operations the same but rewrite the snippet in PHP. | package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}
| <?php
function stripchars($s, $chars) {
return str_replace(str_split($chars), "", $s);
}
echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
?>
|
Port the provided Go code into PHP while preserving the original functionality. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
if len(a) > 1 && !recurse(len(a) - 1) {
panic("sorted permutation not found!")
}
fmt.Println("after: ", a)
}
func recurse(last int) bool {
if last <= 0 {
for i := len(a) - 1; a[i] >= a[i-1]; i-- {
if i == 1 {
return true
}
}
return false
}
for i := 0; i <= last; i++ {
a[i], a[last] = a[last], a[i]
if recurse(last - 1) {
return true
}
a[i], a[last] = a[last], a[i]
}
return false
}
| function inOrder($arr){
for($i=0;$i<count($arr);$i++){
if(isset($arr[$i+1])){
if($arr[$i] > $arr[$i+1]){
return false;
}
}
}
return true;
}
function permute($items, $perms = array( )) {
if (empty($items)) {
if(inOrder($perms)){
return $perms;
}
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permute($newitems, $newperms);
if($res){
return $res;
}
}
}
}
$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);
$arr = permute($arr);
echo implode(',',$arr);
|
Write a version of this Go function in PHP with identical behavior. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
if len(a) > 1 && !recurse(len(a) - 1) {
panic("sorted permutation not found!")
}
fmt.Println("after: ", a)
}
func recurse(last int) bool {
if last <= 0 {
for i := len(a) - 1; a[i] >= a[i-1]; i-- {
if i == 1 {
return true
}
}
return false
}
for i := 0; i <= last; i++ {
a[i], a[last] = a[last], a[i]
if recurse(last - 1) {
return true
}
a[i], a[last] = a[last], a[i]
}
return false
}
| function inOrder($arr){
for($i=0;$i<count($arr);$i++){
if(isset($arr[$i+1])){
if($arr[$i] > $arr[$i+1]){
return false;
}
}
}
return true;
}
function permute($items, $perms = array( )) {
if (empty($items)) {
if(inOrder($perms)){
return $perms;
}
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permute($newitems, $newperms);
if($res){
return $res;
}
}
}
}
$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);
$arr = permute($arr);
echo implode(',',$arr);
|
Change the programming language of this snippet from Go to PHP without modifying what it does. | package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{},
[]float64{math.Inf(1), math.Inf(1)},
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}
| $nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";
|
Maintain the same structure and functionality when rewriting this code in PHP. | package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{},
[]float64{math.Inf(1), math.Inf(1)},
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}
| $nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";
|
Convert the following code from Go to PHP, ensuring the logic remains intact. | package main
import (
"fmt"
"math"
"strings"
)
func main(){
fmt.Println(H("1223334444"))
}
func H(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
}
| <?php
function shannonEntropy($string) {
$h = 0.0;
$len = strlen($string);
foreach (count_chars($string, 1) as $count) {
$h -= (double) ($count / $len) * log((double) ($count / $len), 2);
}
return $h;
}
$strings = array(
'1223334444',
'1225554444',
'aaBBcccDDDD',
'122333444455555',
'Rosetta Code',
'1234567890abcdefghijklmnopqrstuvwxyz',
);
foreach ($strings AS $string) {
printf(
'%36s : %s' . PHP_EOL,
$string,
number_format(shannonEntropy($string), 6)
);
}
|
Transform the following Go implementation into PHP, maintaining the same output and logic. | package main
import (
"fmt"
"math"
"strings"
)
func main(){
fmt.Println(H("1223334444"))
}
func H(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
}
| <?php
function shannonEntropy($string) {
$h = 0.0;
$len = strlen($string);
foreach (count_chars($string, 1) as $count) {
$h -= (double) ($count / $len) * log((double) ($count / $len), 2);
}
return $h;
}
$strings = array(
'1223334444',
'1225554444',
'aaBBcccDDDD',
'122333444455555',
'Rosetta Code',
'1234567890abcdefghijklmnopqrstuvwxyz',
);
foreach ($strings AS $string) {
printf(
'%36s : %s' . PHP_EOL,
$string,
number_format(shannonEntropy($string), 6)
);
}
|
Change the programming language of this snippet from Go to PHP without modifying what it does. | package main
import "fmt"
func main() { fmt.Println("Hello world!") }
| <?php
echo "Hello world!\n";
?>
|
Ensure the translated PHP code behaves exactly like the original Go snippet. | package main
import "fmt"
func main() { fmt.Println("Hello world!") }
| <?php
echo "Hello world!\n";
?>
|
Write a version of this Go function in PHP with identical behavior. | package main
import "fmt"
func main() {
a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
fmt.Println(a)
fmt.Println(fd(a, 9))
}
func fd(a []int, ord int) []int {
for i := 0; i < ord; i++ {
for j := 0; j < len(a)-i-1; j++ {
a[j] = a[j+1] - a[j]
}
}
return a[:len(a)-ord]
}
| <?php
function forwardDiff($anArray, $times = 1) {
if ($times <= 0) { return $anArray; }
for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) {
$accumilation[] = $anArray[$i] - $anArray[$i - 1];
}
if ($times === 1) { return $accumilation; }
return forwardDiff($accumilation, $times - 1);
}
class ForwardDiffExample extends PweExample {
function _should_run_empty_array_for_single_elem() {
$expected = array($this->rand()->int());
$this->spec(forwardDiff($expected))->shouldEqual(array());
}
function _should_give_diff_of_two_elem_as_single_elem() {
$twoNums = array($this->rand()->int(), $this->rand()->int());
$expected = array($twoNums[1] - $twoNums[0]);
$this->spec(forwardDiff($twoNums))->shouldEqual($expected);
}
function _should_compute_correct_forward_diff_for_longer_arrays() {
$diffInput = array(10, 2, 9, 6, 5);
$expected = array(-8, 7, -3, -1);
$this->spec(forwardDiff($diffInput))->shouldEqual($expected);
}
function _should_apply_more_than_once_if_specified() {
$diffInput = array(4, 6, 9, 3, 4);
$expectedAfter1 = array(2, 3, -6, 1);
$expectedAfter2 = array(1, -9, 7);
$this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);
$this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);
}
function _should_return_array_unaltered_if_no_times() {
$this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);
}
}
|
Translate this program into PHP but keep the logic exactly as in Go. | package main
import "fmt"
func main() {
a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
fmt.Println(a)
fmt.Println(fd(a, 9))
}
func fd(a []int, ord int) []int {
for i := 0; i < ord; i++ {
for j := 0; j < len(a)-i-1; j++ {
a[j] = a[j+1] - a[j]
}
}
return a[:len(a)-ord]
}
| <?php
function forwardDiff($anArray, $times = 1) {
if ($times <= 0) { return $anArray; }
for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) {
$accumilation[] = $anArray[$i] - $anArray[$i - 1];
}
if ($times === 1) { return $accumilation; }
return forwardDiff($accumilation, $times - 1);
}
class ForwardDiffExample extends PweExample {
function _should_run_empty_array_for_single_elem() {
$expected = array($this->rand()->int());
$this->spec(forwardDiff($expected))->shouldEqual(array());
}
function _should_give_diff_of_two_elem_as_single_elem() {
$twoNums = array($this->rand()->int(), $this->rand()->int());
$expected = array($twoNums[1] - $twoNums[0]);
$this->spec(forwardDiff($twoNums))->shouldEqual($expected);
}
function _should_compute_correct_forward_diff_for_longer_arrays() {
$diffInput = array(10, 2, 9, 6, 5);
$expected = array(-8, 7, -3, -1);
$this->spec(forwardDiff($diffInput))->shouldEqual($expected);
}
function _should_apply_more_than_once_if_specified() {
$diffInput = array(4, 6, 9, 3, 4);
$expectedAfter1 = array(2, 3, -6, 1);
$expectedAfter2 = array(1, -9, 7);
$this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);
$this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);
}
function _should_return_array_unaltered_if_no_times() {
$this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);
}
}
|
Translate the given Go code snippet into PHP without altering its behavior. | func IsPrime(n int) bool {
if n < 0 { n = -n }
switch {
case n == 2:
return true
case n < 2 || n % 2 == 0:
return false
default:
for i = 3; i*i <= n; i += 2 {
if n % i == 0 { return false }
}
}
return true
}
| <?php
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
return false;
$limit = sqrt($a);
for ($i = 2; $i <= $limit; $i++)
if ($a % $i == 0)
return false;
return true;
}
foreach (range(1, 100) as $x)
if (prime($x)) echo "$x\n";
?>
|
Produce a functionally identical PHP code for the snippet given in Go. | func IsPrime(n int) bool {
if n < 0 { n = -n }
switch {
case n == 2:
return true
case n < 2 || n % 2 == 0:
return false
default:
for i = 3; i*i <= n; i += 2 {
if n % i == 0 { return false }
}
}
return true
}
| <?php
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
return false;
$limit = sqrt($a);
for ($i = 2; $i <= $limit; $i++)
if ($a % $i == 0)
return false;
return true;
}
foreach (range(1, 100) as $x)
if (prime($x)) echo "$x\n";
?>
|
Rewrite the snippet below in PHP so it works the same as the original Go code. | package main
import "fmt"
import "math/big"
func main() {
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
}
| <?php
$n=5;
$k=3;
function factorial($val){
for($f=2;$val-1>1;$f*=$val--);
return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the Go version. | package main
import "fmt"
import "math/big"
func main() {
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
}
| <?php
$n=5;
$k=3;
function factorial($val){
for($f=2;$val-1>1;$f*=$val--);
return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?>
|
Write the same algorithm in PHP as shown in this Go implementation. | package main
import "fmt"
func main() {
var a []interface{}
a = append(a, 3)
a = append(a, "apples", "oranges")
fmt.Println(a)
}
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Produce a language-to-language conversion: from Go to PHP, same semantics. | package main
import "fmt"
func main() {
var a []interface{}
a = append(a, 3)
a = append(a, "apples", "oranges")
fmt.Println(a)
}
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Translate this program into PHP but keep the logic exactly as in Go. | package raster
import (
"fmt"
"io"
"os"
)
func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
if _, err = fmt.Fprintln(w, "P6"); err != nil {
return
}
for _, c := range b.Comments {
if _, err = fmt.Fprintln(w, c); err != nil {
return
}
}
_, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
if err != nil {
return
}
b3 := make([]byte, 3*len(b.px))
n1 := 0
for _, px := range b.px {
b3[n1] = px.R
b3[n1+1] = px.G
b3[n1+2] = px.B
n1 += 3
}
if _, err = w.Write(b3); err != nil {
return
}
return
}
func (b *Bitmap) WritePpmFile(fn string) (err error) {
var f *os.File
if f, err = os.Create(fn); err != nil {
return
}
if err = b.WritePpmTo(f); err != nil {
return
}
return f.Close()
}
| 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');
|
Transform the following Go implementation into PHP, maintaining the same output and logic. | package raster
import (
"fmt"
"io"
"os"
)
func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
if _, err = fmt.Fprintln(w, "P6"); err != nil {
return
}
for _, c := range b.Comments {
if _, err = fmt.Fprintln(w, c); err != nil {
return
}
}
_, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
if err != nil {
return
}
b3 := make([]byte, 3*len(b.px))
n1 := 0
for _, px := range b.px {
b3[n1] = px.R
b3[n1+1] = px.G
b3[n1+2] = px.B
n1 += 3
}
if _, err = w.Write(b3); err != nil {
return
}
return
}
func (b *Bitmap) WritePpmFile(fn string) (err error) {
var f *os.File
if f, err = os.Create(fn); err != nil {
return
}
if err = b.WritePpmTo(f); err != nil {
return
}
return f.Close()
}
| 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');
|
Rewrite the snippet below in PHP so it works the same as the original Go code. | package main
import "os"
func main() {
os.Remove("input.txt")
os.Remove("/input.txt")
os.Remove("docs")
os.Remove("/docs")
os.RemoveAll("docs")
os.RemoveAll("/docs")
}
| <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
|
Change the programming language of this snippet from Go to PHP without modifying what it does. | package main
import "os"
func main() {
os.Remove("input.txt")
os.Remove("/input.txt")
os.Remove("docs")
os.Remove("/docs")
os.RemoveAll("docs")
os.RemoveAll("/docs")
}
| <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
|
Ensure the translated PHP code behaves exactly like the original Go snippet. | package ddate
import (
"strconv"
"strings"
"time"
)
const (
DefaultFmt = "Pungenday, Discord 5, 3131 YOLD"
OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131
Celebrate Mojoday`
)
const (
protoLongSeason = "Discord"
protoShortSeason = "Dsc"
protoLongDay = "Pungenday"
protoShortDay = "PD"
protoOrdDay = "5"
protoCardDay = "5th"
protoHolyday = "Mojoday"
protoYear = "3131"
)
var (
longDay = []string{"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"}
shortDay = []string{"SM", "BT", "PD", "PP", "SO"}
longSeason = []string{
"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}
shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"}
holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"},
{"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}}
)
type DiscDate struct {
StTibs bool
Dayy int
Year int
}
func New(eris time.Time) DiscDate {
t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),
eris.Second(), eris.Nanosecond(), eris.Location())
bob := int(eris.Sub(t).Hours()) / 24
raw := eris.Year()
hastur := DiscDate{Year: raw + 1166}
if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {
if bob > 59 {
bob--
} else if bob == 59 {
hastur.StTibs = true
return hastur
}
}
hastur.Dayy = bob
return hastur
}
func (dd DiscDate) Format(f string) (r string) {
var st, snarf string
var dateElement bool
f6 := func(proto, wibble string) {
if !dateElement {
snarf = r
dateElement = true
}
if st > "" {
r = ""
} else {
r += wibble
}
f = f[len(proto):]
}
f4 := func(proto, wibble string) {
if dd.StTibs {
st = "St. Tib's Day"
}
f6(proto, wibble)
}
season, day := dd.Dayy/73, dd.Dayy%73
for f > "" {
switch {
case strings.HasPrefix(f, protoLongDay):
f4(protoLongDay, longDay[dd.Dayy%5])
case strings.HasPrefix(f, protoShortDay):
f4(protoShortDay, shortDay[dd.Dayy%5])
case strings.HasPrefix(f, protoCardDay):
funkychickens := "th"
if day/10 != 1 {
switch day % 10 {
case 0:
funkychickens = "st"
case 1:
funkychickens = "nd"
case 2:
funkychickens = "rd"
}
}
f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)
case strings.HasPrefix(f, protoOrdDay):
f4(protoOrdDay, strconv.Itoa(day+1))
case strings.HasPrefix(f, protoLongSeason):
f6(protoLongSeason, longSeason[season])
case strings.HasPrefix(f, protoShortSeason):
f6(protoShortSeason, shortSeason[season])
case strings.HasPrefix(f, protoHolyday):
if day == 4 {
r += holyday[season][0]
} else if day == 49 {
r += holyday[season][1]
}
f = f[len(protoHolyday):]
case strings.HasPrefix(f, protoYear):
r += strconv.Itoa(dd.Year)
f = f[4:]
default:
r += f[:1]
f = f[1:]
}
}
if st > "" {
r = snarf + st + r
}
return
}
| <?php
$Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);
$MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath");
$DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle");
$Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');
$Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay");
$Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux");
$edate = explode(" ",date('Y m j L'));
$usery = $edate[0];
$userm = $edate[1];
$userd = $edate[2];
$IsLeap = $edate[3];
if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {
$usery = $_GET['y'];
$userm = $_GET['m'];
$userd = $_GET['d'];
$IsLeap = 0;
if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;
if ($usery%400 == 0) $IsLeap = 1;
}
$userdays = 0;
$i = 0;
while ($i < ($userm-1)) {
$userdays = $userdays + $Anerisia[$i];
$i = $i +1;
}
$userdays = $userdays + $userd;
$IsHolyday = 0;
$dyear = $usery + 1166;
$dmonth = $MONTHS[$userdays/73.2];
$dday = $userdays%73;
if (0 == $dday) $dday = 73;
$Dname = $DAYS[$userdays%5];
$Holyday = "St. Tibs Day";
if ($dday == 5) {
$Holyday = $Holy5[$userdays/73.2];
$IsHolyday =1;
}
if ($dday == 50) {
$Holyday = $Holy50[$userdays/73.2];
$IsHolyday =1;
}
if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;
$suff = $Dsuff[$dday%10] ;
if ((11 <= $dday) && (19 >= $dday)) $suff='th';
if ($IsHolyday ==2)
echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear;
if ($IsHolyday ==1)
echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday;
if ($IsHolyday == 0)
echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear;
?>
|
Convert this Go snippet to PHP and keep its semantics consistent. | package ddate
import (
"strconv"
"strings"
"time"
)
const (
DefaultFmt = "Pungenday, Discord 5, 3131 YOLD"
OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131
Celebrate Mojoday`
)
const (
protoLongSeason = "Discord"
protoShortSeason = "Dsc"
protoLongDay = "Pungenday"
protoShortDay = "PD"
protoOrdDay = "5"
protoCardDay = "5th"
protoHolyday = "Mojoday"
protoYear = "3131"
)
var (
longDay = []string{"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"}
shortDay = []string{"SM", "BT", "PD", "PP", "SO"}
longSeason = []string{
"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}
shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"}
holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"},
{"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}}
)
type DiscDate struct {
StTibs bool
Dayy int
Year int
}
func New(eris time.Time) DiscDate {
t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),
eris.Second(), eris.Nanosecond(), eris.Location())
bob := int(eris.Sub(t).Hours()) / 24
raw := eris.Year()
hastur := DiscDate{Year: raw + 1166}
if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {
if bob > 59 {
bob--
} else if bob == 59 {
hastur.StTibs = true
return hastur
}
}
hastur.Dayy = bob
return hastur
}
func (dd DiscDate) Format(f string) (r string) {
var st, snarf string
var dateElement bool
f6 := func(proto, wibble string) {
if !dateElement {
snarf = r
dateElement = true
}
if st > "" {
r = ""
} else {
r += wibble
}
f = f[len(proto):]
}
f4 := func(proto, wibble string) {
if dd.StTibs {
st = "St. Tib's Day"
}
f6(proto, wibble)
}
season, day := dd.Dayy/73, dd.Dayy%73
for f > "" {
switch {
case strings.HasPrefix(f, protoLongDay):
f4(protoLongDay, longDay[dd.Dayy%5])
case strings.HasPrefix(f, protoShortDay):
f4(protoShortDay, shortDay[dd.Dayy%5])
case strings.HasPrefix(f, protoCardDay):
funkychickens := "th"
if day/10 != 1 {
switch day % 10 {
case 0:
funkychickens = "st"
case 1:
funkychickens = "nd"
case 2:
funkychickens = "rd"
}
}
f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)
case strings.HasPrefix(f, protoOrdDay):
f4(protoOrdDay, strconv.Itoa(day+1))
case strings.HasPrefix(f, protoLongSeason):
f6(protoLongSeason, longSeason[season])
case strings.HasPrefix(f, protoShortSeason):
f6(protoShortSeason, shortSeason[season])
case strings.HasPrefix(f, protoHolyday):
if day == 4 {
r += holyday[season][0]
} else if day == 49 {
r += holyday[season][1]
}
f = f[len(protoHolyday):]
case strings.HasPrefix(f, protoYear):
r += strconv.Itoa(dd.Year)
f = f[4:]
default:
r += f[:1]
f = f[1:]
}
}
if st > "" {
r = snarf + st + r
}
return
}
| <?php
$Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);
$MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath");
$DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle");
$Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');
$Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay");
$Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux");
$edate = explode(" ",date('Y m j L'));
$usery = $edate[0];
$userm = $edate[1];
$userd = $edate[2];
$IsLeap = $edate[3];
if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {
$usery = $_GET['y'];
$userm = $_GET['m'];
$userd = $_GET['d'];
$IsLeap = 0;
if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;
if ($usery%400 == 0) $IsLeap = 1;
}
$userdays = 0;
$i = 0;
while ($i < ($userm-1)) {
$userdays = $userdays + $Anerisia[$i];
$i = $i +1;
}
$userdays = $userdays + $userd;
$IsHolyday = 0;
$dyear = $usery + 1166;
$dmonth = $MONTHS[$userdays/73.2];
$dday = $userdays%73;
if (0 == $dday) $dday = 73;
$Dname = $DAYS[$userdays%5];
$Holyday = "St. Tibs Day";
if ($dday == 5) {
$Holyday = $Holy5[$userdays/73.2];
$IsHolyday =1;
}
if ($dday == 50) {
$Holyday = $Holy50[$userdays/73.2];
$IsHolyday =1;
}
if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;
$suff = $Dsuff[$dday%10] ;
if ((11 <= $dday) && (19 >= $dday)) $suff='th';
if ($IsHolyday ==2)
echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear;
if ($IsHolyday ==1)
echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday;
if ($IsHolyday == 0)
echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear;
?>
|
Please provide an equivalent version of this Go code in PHP. | package main
import (
"fmt"
)
func main() {
str := "Mary had a %s lamb"
txt := "little"
out := fmt.Sprintf(str, txt)
fmt.Println(out)
}
| <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
|
Write the same algorithm in PHP as shown in this Go implementation. | package main
import (
"fmt"
)
func main() {
str := "Mary had a %s lamb"
txt := "little"
out := fmt.Sprintf(str, txt)
fmt.Println(out)
}
| <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
|
Produce a functionally identical PHP code for the snippet given in Go. | package main
import (
"fmt"
"container/heap"
"sort"
)
type IntPile []int
func (self IntPile) Top() int { return self[len(self)-1] }
func (self *IntPile) Pop() int {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
type IntPilesHeap []IntPile
func (self IntPilesHeap) Len() int { return len(self) }
func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }
func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }
func (self *IntPilesHeap) Pop() interface{} {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
func patience_sort (n []int) {
var piles []IntPile
for _, x := range n {
j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })
if j != len(piles) {
piles[j] = append(piles[j], x)
} else {
piles = append(piles, IntPile{ x })
}
}
hp := IntPilesHeap(piles)
heap.Init(&hp)
for i, _ := range n {
smallPile := heap.Pop(&hp).(IntPile)
n[i] = smallPile.Pop()
if len(smallPile) != 0 {
heap.Push(&hp, smallPile)
}
}
if len(hp) != 0 {
panic("something went wrong")
}
}
func main() {
a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}
patience_sort(a)
fmt.Println(a)
}
| <?php
class PilesHeap extends SplMinHeap {
public function compare($pile1, $pile2) {
return parent::compare($pile1->top(), $pile2->top());
}
}
function patience_sort(&$n) {
$piles = array();
foreach ($n as $x) {
$low = 0; $high = count($piles)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($piles[$mid]->top() >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
if ($i == count($piles))
$piles[] = new SplStack();
$piles[$i]->push($x);
}
$heap = new PilesHeap();
foreach ($piles as $pile)
$heap->insert($pile);
for ($c = 0; $c < count($n); $c++) {
$smallPile = $heap->extract();
$n[$c] = $smallPile->pop();
if (!$smallPile->isEmpty())
$heap->insert($smallPile);
}
assert($heap->isEmpty());
}
$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
|
Produce a language-to-language conversion: from Go to PHP, same semantics. | package main
import (
"fmt"
"container/heap"
"sort"
)
type IntPile []int
func (self IntPile) Top() int { return self[len(self)-1] }
func (self *IntPile) Pop() int {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
type IntPilesHeap []IntPile
func (self IntPilesHeap) Len() int { return len(self) }
func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }
func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }
func (self *IntPilesHeap) Pop() interface{} {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
func patience_sort (n []int) {
var piles []IntPile
for _, x := range n {
j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })
if j != len(piles) {
piles[j] = append(piles[j], x)
} else {
piles = append(piles, IntPile{ x })
}
}
hp := IntPilesHeap(piles)
heap.Init(&hp)
for i, _ := range n {
smallPile := heap.Pop(&hp).(IntPile)
n[i] = smallPile.Pop()
if len(smallPile) != 0 {
heap.Push(&hp, smallPile)
}
}
if len(hp) != 0 {
panic("something went wrong")
}
}
func main() {
a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}
patience_sort(a)
fmt.Println(a)
}
| <?php
class PilesHeap extends SplMinHeap {
public function compare($pile1, $pile2) {
return parent::compare($pile1->top(), $pile2->top());
}
}
function patience_sort(&$n) {
$piles = array();
foreach ($n as $x) {
$low = 0; $high = count($piles)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($piles[$mid]->top() >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
if ($i == count($piles))
$piles[] = new SplStack();
$piles[$i]->push($x);
}
$heap = new PilesHeap();
foreach ($piles as $pile)
$heap->insert($pile);
for ($c = 0; $c < count($n); $c++) {
$smallPile = $heap->extract();
$n[$c] = $smallPile->pop();
if (!$smallPile->isEmpty())
$heap->insert($smallPile);
}
assert($heap->isEmpty());
}
$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
|
Write a version of this Go function in PHP with identical behavior. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
)
var rows, cols int
var rx, cx int
var mn []int
func main() {
src, err := ioutil.ReadFile("ww.config")
if err != nil {
fmt.Println(err)
return
}
srcRows := bytes.Split(src, []byte{'\n'})
rows = len(srcRows)
for _, r := range srcRows {
if len(r) > cols {
cols = len(r)
}
}
rx, cx = rows+2, cols+2
mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}
odd := make([]byte, rx*cx)
even := make([]byte, rx*cx)
for ri, r := range srcRows {
copy(odd[(ri+1)*cx+1:], r)
}
for {
print(odd)
step(even, odd)
fmt.Scanln()
print(even)
step(odd, even)
fmt.Scanln()
}
}
func print(grid []byte) {
fmt.Println(strings.Repeat("__", cols))
fmt.Println()
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
if grid[r*cx+c] == 0 {
fmt.Print(" ")
} else {
fmt.Printf(" %c", grid[r*cx+c])
}
}
fmt.Println()
}
}
func step(dst, src []byte) {
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
x := r*cx + c
dst[x] = src[x]
switch dst[x] {
case 'H':
dst[x] = 't'
case 't':
dst[x] = '.'
case '.':
var nn int
for _, n := range mn {
if src[x+n] == 'H' {
nn++
}
}
if nn == 1 || nn == 2 {
dst[x] = 'H'
}
}
}
}
}
| $desc = 'tH.........
. .
........
. .
Ht.. ......
..
tH.... .......
..
..
tH..... ......
..';
$steps = 30;
$world = array(array());
$row = 0;
$col = 0;
foreach(str_split($desc) as $i){
switch($i){
case "\n":
$row++;
$col = 0;
$world[] = array();
break;
case '.':
$world[$row][$col] = 1;//conductor
$col++;
break;
case 'H':
$world[$row][$col] = 2;//head
$col++;
break;
case 't':
$world[$row][$col] = 3;//tail
$col++;
break;
default:
$world[$row][$col] = 0;//insulator/air
$col++;
break;
};
};
function draw_world($world){
foreach($world as $rowc){
foreach($rowc as $cell){
switch($cell){
case 0:
echo ' ';
break;
case 1:
echo '.';
break;
case 2:
echo 'H';
break;
case 3:
echo 't';
};
};
echo "\n";
};
};
echo "Original world:\n";
draw_world($world);
for($i = 0; $i < $steps; $i++){
$old_world = $world; //backup to look up where was an electron head
foreach($world as $row => &$rowc){
foreach($rowc as $col => &$cell){
switch($cell){
case 2:
$cell = 3;
break;
case 3:
$cell = 1;
break;
case 1:
$neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col] == 2;
if($neigh_heads == 1 || $neigh_heads == 2){
$cell = 2;
};
};
};
unset($cell); //just to be safe
};
unset($rowc); //just to be safe
echo "\nStep " . ($i + 1) . ":\n";
draw_world($world);
};
|
Change the following Go code into PHP without altering its purpose. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
)
var rows, cols int
var rx, cx int
var mn []int
func main() {
src, err := ioutil.ReadFile("ww.config")
if err != nil {
fmt.Println(err)
return
}
srcRows := bytes.Split(src, []byte{'\n'})
rows = len(srcRows)
for _, r := range srcRows {
if len(r) > cols {
cols = len(r)
}
}
rx, cx = rows+2, cols+2
mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}
odd := make([]byte, rx*cx)
even := make([]byte, rx*cx)
for ri, r := range srcRows {
copy(odd[(ri+1)*cx+1:], r)
}
for {
print(odd)
step(even, odd)
fmt.Scanln()
print(even)
step(odd, even)
fmt.Scanln()
}
}
func print(grid []byte) {
fmt.Println(strings.Repeat("__", cols))
fmt.Println()
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
if grid[r*cx+c] == 0 {
fmt.Print(" ")
} else {
fmt.Printf(" %c", grid[r*cx+c])
}
}
fmt.Println()
}
}
func step(dst, src []byte) {
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
x := r*cx + c
dst[x] = src[x]
switch dst[x] {
case 'H':
dst[x] = 't'
case 't':
dst[x] = '.'
case '.':
var nn int
for _, n := range mn {
if src[x+n] == 'H' {
nn++
}
}
if nn == 1 || nn == 2 {
dst[x] = 'H'
}
}
}
}
}
| $desc = 'tH.........
. .
........
. .
Ht.. ......
..
tH.... .......
..
..
tH..... ......
..';
$steps = 30;
$world = array(array());
$row = 0;
$col = 0;
foreach(str_split($desc) as $i){
switch($i){
case "\n":
$row++;
$col = 0;
$world[] = array();
break;
case '.':
$world[$row][$col] = 1;//conductor
$col++;
break;
case 'H':
$world[$row][$col] = 2;//head
$col++;
break;
case 't':
$world[$row][$col] = 3;//tail
$col++;
break;
default:
$world[$row][$col] = 0;//insulator/air
$col++;
break;
};
};
function draw_world($world){
foreach($world as $rowc){
foreach($rowc as $cell){
switch($cell){
case 0:
echo ' ';
break;
case 1:
echo '.';
break;
case 2:
echo 'H';
break;
case 3:
echo 't';
};
};
echo "\n";
};
};
echo "Original world:\n";
draw_world($world);
for($i = 0; $i < $steps; $i++){
$old_world = $world; //backup to look up where was an electron head
foreach($world as $row => &$rowc){
foreach($rowc as $col => &$cell){
switch($cell){
case 2:
$cell = 3;
break;
case 3:
$cell = 1;
break;
case 1:
$neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col] == 2;
if($neigh_heads == 1 || $neigh_heads == 2){
$cell = 2;
};
};
};
unset($cell); //just to be safe
};
unset($rowc); //just to be safe
echo "\nStep " . ($i + 1) . ":\n";
draw_world($world);
};
|
Convert this Go block to PHP, preserving its control flow and logic. | package main
import (
"fmt"
"math"
)
type xy struct {
x, y float64
}
type seg struct {
p1, p2 xy
}
type poly struct {
name string
sides []seg
}
func inside(pt xy, pg poly) (i bool) {
for _, side := range pg.sides {
if rayIntersectsSegment(pt, side) {
i = !i
}
}
return
}
func rayIntersectsSegment(p xy, s seg) bool {
var a, b xy
if s.p1.y < s.p2.y {
a, b = s.p1, s.p2
} else {
a, b = s.p2, s.p1
}
for p.y == a.y || p.y == b.y {
p.y = math.Nextafter(p.y, math.Inf(1))
}
if p.y < a.y || p.y > b.y {
return false
}
if a.x > b.x {
if p.x > a.x {
return false
}
if p.x < b.x {
return true
}
} else {
if p.x > b.x {
return false
}
if p.x < a.x {
return true
}
}
return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)
}
var (
p1 = xy{0, 0}
p2 = xy{10, 0}
p3 = xy{10, 10}
p4 = xy{0, 10}
p5 = xy{2.5, 2.5}
p6 = xy{7.5, 2.5}
p7 = xy{7.5, 7.5}
p8 = xy{2.5, 7.5}
p9 = xy{0, 5}
p10 = xy{10, 5}
p11 = xy{3, 0}
p12 = xy{7, 0}
p13 = xy{7, 10}
p14 = xy{3, 10}
)
var tpg = []poly{
{"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},
{"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},
{p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},
{"strange", []seg{{p1, p5},
{p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},
{"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13},
{p13, p14}, {p14, p9}, {p9, p11}}},
}
var tpt = []xy{
{5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},
{1, 2}, {2, 1},
}
func main() {
for _, pg := range tpg {
fmt.Printf("%s:\n", pg.name)
for _, pt := range tpt {
fmt.Println(pt, inside(pt, pg))
}
}
}
| <?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;
}
}
|
Ensure the translated PHP code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"math"
)
type xy struct {
x, y float64
}
type seg struct {
p1, p2 xy
}
type poly struct {
name string
sides []seg
}
func inside(pt xy, pg poly) (i bool) {
for _, side := range pg.sides {
if rayIntersectsSegment(pt, side) {
i = !i
}
}
return
}
func rayIntersectsSegment(p xy, s seg) bool {
var a, b xy
if s.p1.y < s.p2.y {
a, b = s.p1, s.p2
} else {
a, b = s.p2, s.p1
}
for p.y == a.y || p.y == b.y {
p.y = math.Nextafter(p.y, math.Inf(1))
}
if p.y < a.y || p.y > b.y {
return false
}
if a.x > b.x {
if p.x > a.x {
return false
}
if p.x < b.x {
return true
}
} else {
if p.x > b.x {
return false
}
if p.x < a.x {
return true
}
}
return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)
}
var (
p1 = xy{0, 0}
p2 = xy{10, 0}
p3 = xy{10, 10}
p4 = xy{0, 10}
p5 = xy{2.5, 2.5}
p6 = xy{7.5, 2.5}
p7 = xy{7.5, 7.5}
p8 = xy{2.5, 7.5}
p9 = xy{0, 5}
p10 = xy{10, 5}
p11 = xy{3, 0}
p12 = xy{7, 0}
p13 = xy{7, 10}
p14 = xy{3, 10}
)
var tpg = []poly{
{"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},
{"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},
{p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},
{"strange", []seg{{p1, p5},
{p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},
{"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13},
{p13, p14}, {p14, p9}, {p9, p11}}},
}
var tpt = []xy{
{5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},
{1, 2}, {2, 1},
}
func main() {
for _, pg := range tpg {
fmt.Printf("%s:\n", pg.name)
for _, pt := range tpt {
fmt.Println(pt, inside(pt, pg))
}
}
}
| <?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;
}
}
|
Please provide an equivalent version of this Go code in PHP. | package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th"))
fmt.Println(strings.Count("ababababab", "abab"))
}
| <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
|
Convert this Go block to PHP, preserving its control flow and logic. | package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th"))
fmt.Println(strings.Count("ababababab", "abab"))
}
| <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
|
Preserve the algorithm and functionality while converting the code from VB to Python. | Debug.Print Hex(&HF0F0 And &HFF00)
Debug.Print Hex(&HF0F0 Or &HFF00)
Debug.Print Hex(&HF0F0 Xor &HFF00)
Debug.Print Hex(Not &HF0F0)
Debug.Print Hex(&HF0F0 Eqv &HFF00)
Debug.Print Hex(&HF0F0 Imp &HFF00)
| def bitwise_built_ins(width, a, b):
mask = (1 << width) - 1
print(f)
def rotr(width, a, n):
"Rotate a, n times to the right"
if n < 0:
return rotl(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return ((a >> n)
| ((a & ((1 << n) - 1))
<< (width - n)))
def rotl(width, a, n):
"Rotate a, n times to the left"
if n < 0:
return rotr(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return (((a << n) & mask)
| (a >> (width - n)))
def asr(width, a, n):
"Arithmetic shift a, n times to the right. (sign preserving)."
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
if n < 0:
return (a << -n) & mask
elif n == 0:
return a
elif n >= width:
return mask if a & top_bit_mask else 0
else:
a = a & mask
if a & top_bit_mask:
signs = (1 << n) - 1
return a >> n | (signs << width - n)
else:
return a >> n
def helper_funcs(width, a):
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
aa = a | top_bit_mask
print(f)
if __name__ == '__main__':
bitwise_built_ins(8, 27, 125)
helper_funcs(8, 27)
|
Rewrite the snippet below in Python so it works the same as the original VB code. | option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
end sub
public sub lt(i):
ori=(ori + i*iang)
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
sub dragon(st,le,dir)
if st=0 then x.fw le: exit sub
x.rt dir
dragon st-1, le/1.41421 ,1
x.rt dir*2
dragon st-1, le/1.41421 ,-1
x.rt dir
end sub
dim x
set x=new turtle
x.iangle=45
x.orient=45
x.incr=1
x.x=200:x.y=200
dragon 12,300,1
set x=nothing
| l = 3
ints = 13
def setup():
size(700, 600)
background(0, 0, 255)
translate(150, 100)
stroke(255)
turn_left(l, ints)
turn_right(l, ints)
def turn_right(l, ints):
if ints == 0:
line(0, 0, 0, -l)
translate(0, -l)
else:
turn_left(l, ints - 1)
rotate(radians(90))
turn_right(l, ints - 1)
def turn_left(l, ints):
if ints == 0:
line(0, 0, 0, -l)
translate(0, -l)
else:
turn_left(l, ints - 1)
rotate(radians(-90))
turn_right(l, ints - 1)
|
Convert this VB snippet to Python and keep its semantics consistent. | $Include "Rapidq.inc"
dim file as qfilestream
if file.open("c:\A Test.txt", fmOpenRead) then
while not File.eof
print File.readline
wend
else
print "Cannot read file"
end if
input "Press enter to exit: ";a$
| for line in lines open('input.txt'):
print line
|
Transform the following VB implementation into Python, maintaining the same output and logic. | Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)
Dim node As New Node(Of T)(value)
a.Next = node
node.Previous = a
b.Previous = node
node.Next = b
End Sub
| def insert(anchor, new):
new.next = anchor.next
new.prev = anchor
anchor.next.prev = new
anchor.next = new
|
Translate this program into Python but keep the logic exactly as in VB. | Dim s As Variant
Private Function quick_select(ByRef s As Variant, k As Integer) As Integer
Dim left As Integer, right As Integer, pos As Integer
Dim pivotValue As Integer, tmp As Integer
left = 1: right = UBound(s)
Do While left < right
pivotValue = s(k)
tmp = s(k)
s(k) = s(right)
s(right) = tmp
pos = left
For i = left To right
If s(i) < pivotValue Then
tmp = s(i)
s(i) = s(pos)
s(pos) = tmp
pos = pos + 1
End If
Next i
tmp = s(right)
s(right) = s(pos)
s(pos) = tmp
If pos = k Then
Exit Do
End If
If pos < k Then
left = pos + 1
Else
right = pos - 1
End If
Loop
quick_select = s(k)
End Function
Public Sub main()
Dim r As Integer, i As Integer
s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]
For i = 1 To 10
r = quick_select(s, i)
Debug.Print IIf(i < 10, r & ", ", "" & r);
Next i
End Sub
| import random
def partition(vector, left, right, pivotIndex):
pivotValue = vector[pivotIndex]
vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]
storeIndex = left
for i in range(left, right):
if vector[i] < pivotValue:
vector[storeIndex], vector[i] = vector[i], vector[storeIndex]
storeIndex += 1
vector[right], vector[storeIndex] = vector[storeIndex], vector[right]
return storeIndex
def _select(vector, left, right, k):
"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive."
while True:
pivotIndex = random.randint(left, right)
pivotNewIndex = partition(vector, left, right, pivotIndex)
pivotDist = pivotNewIndex - left
if pivotDist == k:
return vector[pivotNewIndex]
elif k < pivotDist:
right = pivotNewIndex - 1
else:
k -= pivotDist + 1
left = pivotNewIndex + 1
def select(vector, k, left=None, right=None):
if left is None:
left = 0
lv1 = len(vector) - 1
if right is None:
right = lv1
assert vector and k >= 0, "Either null vector or k < 0 "
assert 0 <= left <= lv1, "left is out of range"
assert left <= right <= lv1, "right is out of range"
return _select(vector, left, right, k)
if __name__ == '__main__':
v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
print([select(v, i) for i in range(10)])
|
Port the provided VB code into Python while preserving the original functionality. | Private Function to_base(ByVal number As Long, base As Integer) As String
Dim digits As String, result As String
Dim i As Integer, digit As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Do While number > 0
digit = number Mod base
result = Mid(digits, digit + 1, 1) & result
number = number \ base
Loop
to_base = result
End Function
Private Function from_base(number As String, base As Integer) As Long
Dim digits As String, result As Long
Dim i As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)
For i = 2 To Len(number)
result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)
Next i
from_base = result
End Function
Public Sub Non_decimal_radices_Convert()
Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub
| i = int('1a',16)
|
Convert the following code from VB to Python, ensuring the logic remains intact. | Private Function to_base(ByVal number As Long, base As Integer) As String
Dim digits As String, result As String
Dim i As Integer, digit As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Do While number > 0
digit = number Mod base
result = Mid(digits, digit + 1, 1) & result
number = number \ base
Loop
to_base = result
End Function
Private Function from_base(number As String, base As Integer) As Long
Dim digits As String, result As Long
Dim i As Integer
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)
For i = 2 To Len(number)
result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)
Next i
from_base = result
End Function
Public Sub Non_decimal_radices_Convert()
Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub
| i = int('1a',16)
|
Produce a language-to-language conversion: from VB to Python, same semantics. | Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Port the provided VB code into Python while preserving the original functionality. | dim crctbl(255)
const crcc =&hEDB88320
sub gencrctable
for i= 0 to 255
k=i
for j=1 to 8
if k and 1 then
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
k=k xor crcc
else
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
end if
next
crctbl(i)=k
next
end sub
function crc32 (buf)
dim r,r1,i
r=&hffffffff
for i=1 to len(buf)
r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0)
r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255)
next
crc32=r xor &hffffffff
end function
gencrctable
wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
| >>> s = 'The quick brown fox jumps over the lazy dog'
>>> import zlib
>>> hex(zlib.crc32(s))
'0x414fa339'
>>> import binascii
>>> hex(binascii.crc32(s))
'0x414fa339'
|
Convert this VB block to Python, preserving its control flow and logic. | Public Sub CSV_TO_HTML()
input_ = "Character,Speech\n" & _
"The multitude,The messiah! Show us the messiah!\n" & _
"Brians mother,<angry>Now you listen here! He
"he
"The multitude,Who are you?\n" & _
"Brians mother,I
"The multitude,Behold his mother! Behold his mother!"
Debug.Print "<table>" & vbCrLf & "<tr><td>"
For i = 1 To Len(input_)
Select Case Mid(input_, i, 1)
Case "\"
If Mid(input_, i + 1, 1) = "n" Then
Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
i = i + 1
Else
Debug.Print Mid(input_, i, 1);
End If
Case ",": Debug.Print "</td><td>";
Case "<": Debug.Print "<";
Case ">": Debug.Print ">";
Case "&": Debug.Print "&";
Case Else: Debug.Print Mid(input_, i, 1);
End Select
Next i
Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub
| csvtxt =
from cgi import escape
def _row2tr(row, attr=None):
cols = escape(row).split(',')
return ('<TR>'
+ ''.join('<TD>%s</TD>' % data for data in cols)
+ '</TR>')
def csv2html(txt):
htmltxt = '<TABLE summary="csv2html program output">\n'
for rownum, row in enumerate(txt.split('\n')):
htmlrow = _row2tr(row)
htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow
htmltxt += htmlrow
htmltxt += '</TABLE>\n'
return htmltxt
htmltxt = csv2html(csvtxt)
print(htmltxt)
|
Convert the following code from VB to Python, ensuring the logic remains intact. | Public Sub CSV_TO_HTML()
input_ = "Character,Speech\n" & _
"The multitude,The messiah! Show us the messiah!\n" & _
"Brians mother,<angry>Now you listen here! He
"he
"The multitude,Who are you?\n" & _
"Brians mother,I
"The multitude,Behold his mother! Behold his mother!"
Debug.Print "<table>" & vbCrLf & "<tr><td>"
For i = 1 To Len(input_)
Select Case Mid(input_, i, 1)
Case "\"
If Mid(input_, i + 1, 1) = "n" Then
Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
i = i + 1
Else
Debug.Print Mid(input_, i, 1);
End If
Case ",": Debug.Print "</td><td>";
Case "<": Debug.Print "<";
Case ">": Debug.Print ">";
Case "&": Debug.Print "&";
Case Else: Debug.Print Mid(input_, i, 1);
End Select
Next i
Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub
| csvtxt =
from cgi import escape
def _row2tr(row, attr=None):
cols = escape(row).split(',')
return ('<TR>'
+ ''.join('<TD>%s</TD>' % data for data in cols)
+ '</TR>')
def csv2html(txt):
htmltxt = '<TABLE summary="csv2html program output">\n'
for rownum, row in enumerate(txt.split('\n')):
htmlrow = _row2tr(row)
htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow
htmltxt += htmlrow
htmltxt += '</TABLE>\n'
return htmltxt
htmltxt = csv2html(csvtxt)
print(htmltxt)
|
Generate an equivalent Python version of this VB code. | Public Sub CSV_TO_HTML()
input_ = "Character,Speech\n" & _
"The multitude,The messiah! Show us the messiah!\n" & _
"Brians mother,<angry>Now you listen here! He
"he
"The multitude,Who are you?\n" & _
"Brians mother,I
"The multitude,Behold his mother! Behold his mother!"
Debug.Print "<table>" & vbCrLf & "<tr><td>"
For i = 1 To Len(input_)
Select Case Mid(input_, i, 1)
Case "\"
If Mid(input_, i + 1, 1) = "n" Then
Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
i = i + 1
Else
Debug.Print Mid(input_, i, 1);
End If
Case ",": Debug.Print "</td><td>";
Case "<": Debug.Print "<";
Case ">": Debug.Print ">";
Case "&": Debug.Print "&";
Case Else: Debug.Print Mid(input_, i, 1);
End Select
Next i
Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub
| csvtxt =
from cgi import escape
def _row2tr(row, attr=None):
cols = escape(row).split(',')
return ('<TR>'
+ ''.join('<TD>%s</TD>' % data for data in cols)
+ '</TR>')
def csv2html(txt):
htmltxt = '<TABLE summary="csv2html program output">\n'
for rownum, row in enumerate(txt.split('\n')):
htmlrow = _row2tr(row)
htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow
htmltxt += htmlrow
htmltxt += '</TABLE>\n'
return htmltxt
htmltxt = csv2html(csvtxt)
print(htmltxt)
|
Write the same code in Python as shown below in VB. | Class NumberContainer
Private TheNumber As Integer
Sub Constructor(InitialNumber As Integer)
TheNumber = InitialNumber
End Sub
Function Number() As Integer
Return TheNumber
End Function
Sub Number(Assigns NewNumber As Integer)
TheNumber = NewNumber
End Sub
End Class
| class MyClass:
name2 = 2
def __init__(self):
self.name1 = 0
def someMethod(self):
self.name1 = 1
MyClass.name2 = 3
myclass = MyClass()
class MyOtherClass:
count = 0
def __init__(self, name, gender="Male", age=None):
MyOtherClass.count += 1
self.name = name
self.gender = gender
if age is not None:
self.age = age
def __del__(self):
MyOtherClass.count -= 1
person1 = MyOtherClass("John")
print person1.name, person1.gender
print person1.age
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age
|
Change the programming language of this snippet from VB to Python without modifying what it does. | Class NumberContainer
Private TheNumber As Integer
Sub Constructor(InitialNumber As Integer)
TheNumber = InitialNumber
End Sub
Function Number() As Integer
Return TheNumber
End Function
Sub Number(Assigns NewNumber As Integer)
TheNumber = NewNumber
End Sub
End Class
| class MyClass:
name2 = 2
def __init__(self):
self.name1 = 0
def someMethod(self):
self.name1 = 1
MyClass.name2 = 3
myclass = MyClass()
class MyOtherClass:
count = 0
def __init__(self, name, gender="Male", age=None):
MyOtherClass.count += 1
self.name = name
self.gender = gender
if age is not None:
self.age = age
def __del__(self):
MyOtherClass.count -= 1
person1 = MyOtherClass("John")
print person1.name, person1.gender
print person1.age
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age
|
Maintain the same structure and functionality when rewriting this code in Python. | Module Module1
ReadOnly max As ULong = 1000000
Function Kaprekar(n As ULong) As Boolean
If n = 1 Then Return True
Dim sq = n * n
Dim sq_str = Str(sq)
Dim l = Len(sq_str)
For x = l - 1 To 1 Step -1
If sq_str(x) = "0" Then
l = l - 1
Else
Exit For
End If
Next
For x = 1 To l - 1
Dim p2 = Val(Mid(sq_str, x + 1))
If p2 > n Then
Continue For
End If
Dim p1 = Val(Left(sq_str, x))
If p1 > n Then Return False
If (p1 + p2) = n Then Return True
Next
Return False
End Function
Sub Main()
Dim count = 0
Console.WriteLine("Kaprekar numbers below 10000")
For n = 1 To max - 1
If Kaprekar(n) Then
count = count + 1
If n < 10000 Then
Console.WriteLine("{0,2} {1,4}", count, n)
End If
End If
Next
Console.WriteLine()
Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
End Sub
End Module
| >>> def k(n):
n2 = str(n**2)
for i in range(len(n2)):
a, b = int(n2[:i] or 0), int(n2[i:])
if b and a + b == n:
return n
>>> [x for x in range(1,10000) if k(x)]
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
>>> len([x for x in range(1,1000000) if k(x)])
54
>>>
|
Produce a functionally identical Python code for the snippet given in VB. | Module Module1
ReadOnly max As ULong = 1000000
Function Kaprekar(n As ULong) As Boolean
If n = 1 Then Return True
Dim sq = n * n
Dim sq_str = Str(sq)
Dim l = Len(sq_str)
For x = l - 1 To 1 Step -1
If sq_str(x) = "0" Then
l = l - 1
Else
Exit For
End If
Next
For x = 1 To l - 1
Dim p2 = Val(Mid(sq_str, x + 1))
If p2 > n Then
Continue For
End If
Dim p1 = Val(Left(sq_str, x))
If p1 > n Then Return False
If (p1 + p2) = n Then Return True
Next
Return False
End Function
Sub Main()
Dim count = 0
Console.WriteLine("Kaprekar numbers below 10000")
For n = 1 To max - 1
If Kaprekar(n) Then
count = count + 1
If n < 10000 Then
Console.WriteLine("{0,2} {1,4}", count, n)
End If
End If
Next
Console.WriteLine()
Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
End Sub
End Module
| >>> def k(n):
n2 = str(n**2)
for i in range(len(n2)):
a, b = int(n2[:i] or 0), int(n2[i:])
if b and a + b == n:
return n
>>> [x for x in range(1,10000) if k(x)]
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
>>> len([x for x in range(1,1000000) if k(x)])
54
>>>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.