Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided PHP code into Go while preserving the original functionality.
<?php $file = fopen(__FILE__, 'r'); // read current file while ($line = fgets($file)) { $line = rtrim($line); // removes linebreaks and spaces at end echo strrev($line) . "\n"; // reverse line and upload it }
package main import ( "bufio" "fmt" "log" "os" ) func init() { log.SetFlags(log.Lshortfile) } func main() { inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) } defer inputFile.Close() scanner := bufio.NewScanner(inputFile) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(scanner.Err()) } }
Produce a language-to-language conversion: from PHP to Go, same semantics.
base_convert("26", 10, 16); // returns "1a"
package main import ( "fmt" "math/big" "strconv" ) func main () { s := strconv.FormatInt(26, 16) fmt.Println(s) i, err := strconv.ParseInt("1a", 16, 64) if err == nil { fmt.Println(i) } b, ok := new(big.Int).SetString("1a", 16) if ok { fmt.Println(b) } }
Transform the following PHP implementation into Go, maintaining the same output and logic.
base_convert("26", 10, 16); // returns "1a"
package main import ( "fmt" "math/big" "strconv" ) func main () { s := strconv.FormatInt(26, 16) fmt.Println(s) i, err := strconv.ParseInt("1a", 16, 64) if err == nil { fmt.Println(i) } b, ok := new(big.Int).SetString("1a", 16) if ok { fmt.Println(b) } }
Write the same code in Go as shown below in PHP.
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Port the following code from PHP to Go with equivalent syntax and logic.
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Maintain the same structure and functionality when rewriting this code in Go.
printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
Convert the following code from PHP to Go, ensuring the logic remains intact.
printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
Convert this PHP snippet to Go and keep its semantics consistent.
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
package main import "fmt" type picnicBasket struct { nServings int corkscrew bool } func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew } func newPicnicBasket(nPeople int) *picnicBasket { return &picnicBasket{nPeople, nPeople > 0} } func main() { var pb picnicBasket pbl := picnicBasket{} pbp := &picnicBasket{} pbn := new(picnicBasket) forTwo := newPicnicBasket(2) forToo := &picnicBasket{nServings: 2, corkscrew: true} fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
Convert the following code from PHP to Go, ensuring the logic remains intact.
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
package main import "fmt" type picnicBasket struct { nServings int corkscrew bool } func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew } func newPicnicBasket(nPeople int) *picnicBasket { return &picnicBasket{nPeople, nPeople > 0} } func main() { var pb picnicBasket pbl := picnicBasket{} pbp := &picnicBasket{} pbn := new(picnicBasket) forTwo := newPicnicBasket(2) forToo := &picnicBasket{nServings: 2, corkscrew: true} fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
Write the same algorithm in Go as shown in this PHP implementation.
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Ensure the translated Go code behaves exactly like the original PHP snippet.
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Keep all operations the same but rewrite the snippet in Go.
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Translate this program into Go but keep the logic exactly as in PHP.
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Port the following code from PHP to Go with equivalent syntax and logic.
class LZW { function compress($unc) { $i;$c;$wc; $w = ""; $dictionary = array(); $result = array(); $dictSize = 256; for ($i = 0; $i < 256; $i += 1) { $dictionary[chr($i)] = $i; } for ($i = 0; $i < strlen($unc); $i++) { $c = $unc[$i]; $wc = $w.$c; if (array_key_exists($w.$c, $dictionary)) { $w = $w.$c; } else { array_push($result,$dictionary[$w]); $dictionary[$wc] = $dictSize++; $w = (string)$c; } } if ($w !== "") { array_push($result,$dictionary[$w]); } return implode(",",$result); } function decompress($com) { $com = explode(",",$com); $i;$w;$k;$result; $dictionary = array(); $entry = ""; $dictSize = 256; for ($i = 0; $i < 256; $i++) { $dictionary[$i] = chr($i); } $w = chr($com[0]); $result = $w; for ($i = 1; $i < count($com);$i++) { $k = $com[$i]; if (isset($dictionary[$k])) { $entry = $dictionary[$k]; } else { if ($k === $dictSize) { $entry = $w.$w[0]; } else { return null; } } $result .= $entry; $dictionary[$dictSize++] = $w . $entry[0]; $w = $entry; } return $result; } } $str = 'TOBEORNOTTOBEORTOBEORNOT'; $lzw = new LZW(); $com = $lzw->compress($str); $dec = $lzw->decompress($com); echo $com . "<br>" . $dec;
package main import ( "fmt" "log" "strings" ) func compress(uncompressed string) []int { dictSize := 256 dictionary := make(map[string]int, dictSize) for i := 0; i < dictSize; i++ { dictionary[string([]byte{byte(i)})] = i } var result []int var w []byte for i := 0; i < len(uncompressed); i++ { c := uncompressed[i] wc := append(w, c) if _, ok := dictionary[string(wc)]; ok { w = wc } else { result = append(result, dictionary[string(w)]) dictionary[string(wc)] = dictSize dictSize++ wc[0] = c w = wc[:1] } } if len(w) > 0 { result = append(result, dictionary[string(w)]) } return result } type BadSymbolError int func (e BadSymbolError) Error() string { return fmt.Sprint("Bad compressed symbol ", int(e)) } func decompress(compressed []int) (string, error) { dictSize := 256 dictionary := make(map[int][]byte, dictSize) for i := 0; i < dictSize; i++ { dictionary[i] = []byte{byte(i)} } var result strings.Builder var w []byte for _, k := range compressed { var entry []byte if x, ok := dictionary[k]; ok { entry = x[:len(x):len(x)] } else if k == dictSize && len(w) > 0 { entry = append(w, w[0]) } else { return result.String(), BadSymbolError(k) } result.Write(entry) if len(w) > 0 { w = append(w, entry[0]) dictionary[dictSize] = w dictSize++ } w = entry } return result.String(), nil } func main() { compressed := compress("TOBEORNOTTOBEORTOBEORNOT") fmt.Println(compressed) decompressed, err := decompress(compressed) if err != nil { log.Fatal(err) } fmt.Println(decompressed) }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
class LZW { function compress($unc) { $i;$c;$wc; $w = ""; $dictionary = array(); $result = array(); $dictSize = 256; for ($i = 0; $i < 256; $i += 1) { $dictionary[chr($i)] = $i; } for ($i = 0; $i < strlen($unc); $i++) { $c = $unc[$i]; $wc = $w.$c; if (array_key_exists($w.$c, $dictionary)) { $w = $w.$c; } else { array_push($result,$dictionary[$w]); $dictionary[$wc] = $dictSize++; $w = (string)$c; } } if ($w !== "") { array_push($result,$dictionary[$w]); } return implode(",",$result); } function decompress($com) { $com = explode(",",$com); $i;$w;$k;$result; $dictionary = array(); $entry = ""; $dictSize = 256; for ($i = 0; $i < 256; $i++) { $dictionary[$i] = chr($i); } $w = chr($com[0]); $result = $w; for ($i = 1; $i < count($com);$i++) { $k = $com[$i]; if (isset($dictionary[$k])) { $entry = $dictionary[$k]; } else { if ($k === $dictSize) { $entry = $w.$w[0]; } else { return null; } } $result .= $entry; $dictionary[$dictSize++] = $w . $entry[0]; $w = $entry; } return $result; } } $str = 'TOBEORNOTTOBEORTOBEORNOT'; $lzw = new LZW(); $com = $lzw->compress($str); $dec = $lzw->decompress($com); echo $com . "<br>" . $dec;
package main import ( "fmt" "log" "strings" ) func compress(uncompressed string) []int { dictSize := 256 dictionary := make(map[string]int, dictSize) for i := 0; i < dictSize; i++ { dictionary[string([]byte{byte(i)})] = i } var result []int var w []byte for i := 0; i < len(uncompressed); i++ { c := uncompressed[i] wc := append(w, c) if _, ok := dictionary[string(wc)]; ok { w = wc } else { result = append(result, dictionary[string(w)]) dictionary[string(wc)] = dictSize dictSize++ wc[0] = c w = wc[:1] } } if len(w) > 0 { result = append(result, dictionary[string(w)]) } return result } type BadSymbolError int func (e BadSymbolError) Error() string { return fmt.Sprint("Bad compressed symbol ", int(e)) } func decompress(compressed []int) (string, error) { dictSize := 256 dictionary := make(map[int][]byte, dictSize) for i := 0; i < dictSize; i++ { dictionary[i] = []byte{byte(i)} } var result strings.Builder var w []byte for _, k := range compressed { var entry []byte if x, ok := dictionary[k]; ok { entry = x[:len(x):len(x)] } else if k == dictSize && len(w) > 0 { entry = append(w, w[0]) } else { return result.String(), BadSymbolError(k) } result.Write(entry) if len(w) > 0 { w = append(w, entry[0]) dictionary[dictSize] = w dictSize++ } w = entry } return result.String(), nil } func main() { compressed := compress("TOBEORNOTTOBEORTOBEORNOT") fmt.Println(compressed) decompressed, err := decompress(compressed) if err != nil { log.Fatal(err) } fmt.Println(decompressed) }
Convert the following code from PHP to Go, ensuring the logic remains intact.
<?php function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); $f = function($n) { // This function must be called using call_user_func() only if ($n < 2) return 1; else { $g = debug_backtrace()[1]['args'][0]; return call_user_func($g, $n-1) + call_user_func($g, $n-2); } }; return call_user_func($f, $n); } echo fib(8), "\n"; ?>
package main import "fmt" func main() { for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} { f, ok := arFib(n) if ok { fmt.Printf("fib %d = %d\n", n, f) } else { fmt.Println("fib undefined for negative numbers") } } } func arFib(n int) (int, bool) { switch { case n < 0: return 0, false case n < 2: return n, true } return yc(func(recurse fn) fn { return func(left, term1, term2 int) int { if left == 0 { return term1+term2 } return recurse(left-1, term1+term2, term1) } })(n-2, 1, 0), true } type fn func(int, int, int) int type ff func(fn) fn type fx func(fx) fn func yc(f ff) fn { return func(x fx) fn { return x(x) }(func(x fx) fn { return f(func(a1, a2, a3 int) int { return x(x)(a1, a2, a3) }) }) }
Produce a functionally identical Go code for the snippet given in PHP.
<?php function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); $f = function($n) { // This function must be called using call_user_func() only if ($n < 2) return 1; else { $g = debug_backtrace()[1]['args'][0]; return call_user_func($g, $n-1) + call_user_func($g, $n-2); } }; return call_user_func($f, $n); } echo fib(8), "\n"; ?>
package main import "fmt" func main() { for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} { f, ok := arFib(n) if ok { fmt.Printf("fib %d = %d\n", n, f) } else { fmt.Println("fib undefined for negative numbers") } } } func arFib(n int) (int, bool) { switch { case n < 0: return 0, false case n < 2: return n, true } return yc(func(recurse fn) fn { return func(left, term1, term2 int) int { if left == 0 { return term1+term2 } return recurse(left-1, term1+term2, term1) } })(n-2, 1, 0), true } type fn func(int, int, int) int type ff func(fn) fn type fx func(fx) fn func yc(f ff) fn { return func(x fx) fn { return x(x) }(func(x fx) fn { return f(func(a1, a2, a3 int) int { return x(x)(a1, a2, a3) }) }) }
Produce a language-to-language conversion: from PHP to Go, same semantics.
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
Convert this PHP block to Go, preserving its control flow and logic.
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
Generate a Go translation of this PHP snippet without changing its computational steps.
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
Translate this program into Go but keep the logic exactly as in PHP.
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
Generate a Go translation of this PHP snippet without changing its computational steps.
<?php echo 'Enter strings (empty string to finish) :', PHP_EOL; $output = $previous = readline(); while ($current = readline()) { $p = $previous; $c = $current; while ($p and $c) { $p = substr($p, 1); $c = substr($c, 1); } if (!$p and !$c) { $output .= PHP_EOL . $current; } if ($c) { $output = $previous = $current; } } echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
package main import ( "bufio" "os" ) func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { recover() defer func() { recover() }() _ = blankLine[0] func() { defer func() { recover() }() _ = s[len(longest)] longest = s }() longest = printLongest(longest) func() { defer func() { recover() os.Stdout.WriteString(s) }() _ = longest[len(s)] s = "" }() }() _ = err.(error) os.Stdout.WriteString(blankLine) blankLine = "" return } printLongest("") }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
<?php echo 'Enter strings (empty string to finish) :', PHP_EOL; $output = $previous = readline(); while ($current = readline()) { $p = $previous; $c = $current; while ($p and $c) { $p = substr($p, 1); $c = substr($c, 1); } if (!$p and !$c) { $output .= PHP_EOL . $current; } if ($c) { $output = $previous = $current; } } echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
package main import ( "bufio" "os" ) func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { recover() defer func() { recover() }() _ = blankLine[0] func() { defer func() { recover() }() _ = s[len(longest)] longest = s }() longest = printLongest(longest) func() { defer func() { recover() os.Stdout.WriteString(s) }() _ = longest[len(s)] s = "" }() }() _ = err.(error) os.Stdout.WriteString(blankLine) blankLine = "" return } printLongest("") }
Produce a functionally identical Go code for the snippet given in PHP.
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
Translate this program into Go but keep the logic exactly as in PHP.
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
Port the following code from PHP to Go with equivalent syntax and logic.
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList(); $remain = new SplDoublyLinkedList(); $sorted->push($lst->shift()); foreach ($lst as $item) { if ($sorted->top() <= $item) { $sorted->push($item); } else { $remain->push($item); } } $result = _merge($sorted, $result); $lst = $remain; } return $result; } function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) { $res = new SplDoublyLinkedList(); while (!$left->isEmpty() && !$right->isEmpty()) { if ($left->bottom() <= $right->bottom()) { $res->push($left->shift()); } else { $res->push($right->shift()); } } foreach ($left as $v) $res->push($v); foreach ($right as $v) $res->push($v); return $res; }
package main import "fmt" type link struct { int next *link } func linkInts(s []int) *link { if len(s) == 0 { return nil } return &link{s[0], linkInts(s[1:])} } func (l *link) String() string { if l == nil { return "nil" } r := fmt.Sprintf("[%d", l.int) for l = l.next; l != nil; l = l.next { r = fmt.Sprintf("%s %d", r, l.int) } return r + "]" } func main() { a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66}) fmt.Println("before:", a) b := strandSort(a) fmt.Println("after: ", b) } func strandSort(a *link) (result *link) { for a != nil { sublist := a a = a.next sTail := sublist for p, pPrev := a, a; p != nil; p = p.next { if p.int > sTail.int { sTail.next = p sTail = p if p == a { a = p.next } else { pPrev.next = p.next } } else { pPrev = p } } sTail.next = nil if result == nil { result = sublist continue } var m, rr *link if sublist.int < result.int { m = sublist sublist = m.next rr = result } else { m = result rr = m.next } result = m for { if sublist == nil { m.next = rr break } if rr == nil { m.next = sublist break } if sublist.int < rr.int { m.next = sublist m = sublist sublist = m.next } else { m.next = rr m = rr rr = m.next } } } return }
Translate the given PHP code snippet into Go without altering its behavior.
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList(); $remain = new SplDoublyLinkedList(); $sorted->push($lst->shift()); foreach ($lst as $item) { if ($sorted->top() <= $item) { $sorted->push($item); } else { $remain->push($item); } } $result = _merge($sorted, $result); $lst = $remain; } return $result; } function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) { $res = new SplDoublyLinkedList(); while (!$left->isEmpty() && !$right->isEmpty()) { if ($left->bottom() <= $right->bottom()) { $res->push($left->shift()); } else { $res->push($right->shift()); } } foreach ($left as $v) $res->push($v); foreach ($right as $v) $res->push($v); return $res; }
package main import "fmt" type link struct { int next *link } func linkInts(s []int) *link { if len(s) == 0 { return nil } return &link{s[0], linkInts(s[1:])} } func (l *link) String() string { if l == nil { return "nil" } r := fmt.Sprintf("[%d", l.int) for l = l.next; l != nil; l = l.next { r = fmt.Sprintf("%s %d", r, l.int) } return r + "]" } func main() { a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66}) fmt.Println("before:", a) b := strandSort(a) fmt.Println("after: ", b) } func strandSort(a *link) (result *link) { for a != nil { sublist := a a = a.next sTail := sublist for p, pPrev := a, a; p != nil; p = p.next { if p.int > sTail.int { sTail.next = p sTail = p if p == a { a = p.next } else { pPrev.next = p.next } } else { pPrev = p } } sTail.next = nil if result == nil { result = sublist continue } var m, rr *link if sublist.int < result.int { m = sublist sublist = m.next rr = result } else { m = result rr = m.next } result = m for { if sublist == nil { m.next = rr break } if rr == nil { m.next = sublist break } if sublist.int < rr.int { m.next = sublist m = sublist sublist = m.next } else { m.next = rr m = rr rr = m.next } } } return }
Produce a language-to-language conversion: from PHP to Go, same semantics.
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, "thing")) return $this->delegate->thing() ; return 'default implementation' ; } } class Delegate { function thing() { return 'Delegate Implementation' ; } } $a = new Delegator() ; print "{$a->operation()}\n" ; $a->delegate = 'A delegate may be any object' ; print "{$a->operation()}\n" ; $a->delegate = new Delegate() ; print "{$a->operation()}\n" ;
package main import "fmt" type Delegator struct { delegate interface{} } type Thingable interface { thing() string } func (self Delegator) operation() string { if v, ok := self.delegate.(Thingable); ok { return v.thing() } return "default implementation" } type Delegate int func (Delegate) thing() string { return "delegate implementation" } func main() { a := Delegator{} fmt.Println(a.operation()) a.delegate = "A delegate may be any object" fmt.Println(a.operation()) var d Delegate a.delegate = d fmt.Println(a.operation()) }
Port the provided PHP code into Go while preserving the original functionality.
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, "thing")) return $this->delegate->thing() ; return 'default implementation' ; } } class Delegate { function thing() { return 'Delegate Implementation' ; } } $a = new Delegator() ; print "{$a->operation()}\n" ; $a->delegate = 'A delegate may be any object' ; print "{$a->operation()}\n" ; $a->delegate = new Delegate() ; print "{$a->operation()}\n" ;
package main import "fmt" type Delegator struct { delegate interface{} } type Thingable interface { thing() string } func (self Delegator) operation() string { if v, ok := self.delegate.(Thingable); ok { return v.thing() } return "default implementation" } type Delegate int func (Delegate) thing() string { return "delegate implementation" } func main() { a := Delegator{} fmt.Println(a.operation()) a.delegate = "A delegate may be any object" fmt.Println(a.operation()) var d Delegate a.delegate = d fmt.Println(a.operation()) }
Translate this program into Go but keep the logic exactly as in PHP.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
Write the same algorithm in Go as shown in this PHP implementation.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
Generate an equivalent Go version of this PHP code.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
Transform the following PHP implementation into Go, maintaining the same output and logic.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
Produce a language-to-language conversion: from PHP to Go, same semantics.
define("PI", 3.14159265358); define("MSG", "Hello World");
package main func main() { s := "immutable" s[0] = 'a' }
Generate a Go translation of this PHP snippet without changing its computational steps.
define("PI", 3.14159265358); define("MSG", "Hello World");
package main func main() { s := "immutable" s[0] = 'a' }
Maintain the same structure and functionality when rewriting this code in Go.
<?php function clip ($subjectPolygon, $clipPolygon) { function inside ($p, $cp1, $cp2) { return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]); } function intersection ($cp1, $cp2, $e, $s) { $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ]; $dp = [ $s[0] - $e[0], $s[1] - $e[1] ]; $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0]; $n2 = $s[0] * $e[1] - $s[1] * $e[0]; $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]); return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3]; } $outputList = $subjectPolygon; $cp1 = end($clipPolygon); foreach ($clipPolygon as $cp2) { $inputList = $outputList; $outputList = []; $s = end($inputList); foreach ($inputList as $e) { if (inside($e, $cp1, $cp2)) { if (!inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $outputList[] = $e; } else if (inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $s = $e; } $cp1 = $cp2; } return $outputList; } $subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]]; $clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]]; $clippedPolygon = clip($subjectPolygon, $clipPolygon); echo json_encode($clippedPolygon); echo "\n"; ?>
package main import "fmt" type point struct { x, y float32 } var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}} var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}} func main() { var cp1, cp2, s, e point inside := func(p point) bool { return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) } intersection := func() (p point) { dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y dpx, dpy := s.x-e.x, s.y-e.y n1 := cp1.x*cp2.y - cp1.y*cp2.x n2 := s.x*e.y - s.y*e.x n3 := 1 / (dcx*dpy - dcy*dpx) p.x = (n1*dpx - n2*dcx) * n3 p.y = (n1*dpy - n2*dcy) * n3 return } outputList := subjectPolygon cp1 = clipPolygon[len(clipPolygon)-1] for _, cp2 = range clipPolygon { inputList := outputList outputList = nil s = inputList[len(inputList)-1] for _, e = range inputList { if inside(e) { if !inside(s) { outputList = append(outputList, intersection()) } outputList = append(outputList, e) } else if inside(s) { outputList = append(outputList, intersection()) } s = e } cp1 = cp2 } fmt.Println(outputList) }
Convert this PHP snippet to Go and keep its semantics consistent.
<?php function clip ($subjectPolygon, $clipPolygon) { function inside ($p, $cp1, $cp2) { return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]); } function intersection ($cp1, $cp2, $e, $s) { $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ]; $dp = [ $s[0] - $e[0], $s[1] - $e[1] ]; $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0]; $n2 = $s[0] * $e[1] - $s[1] * $e[0]; $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]); return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3]; } $outputList = $subjectPolygon; $cp1 = end($clipPolygon); foreach ($clipPolygon as $cp2) { $inputList = $outputList; $outputList = []; $s = end($inputList); foreach ($inputList as $e) { if (inside($e, $cp1, $cp2)) { if (!inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $outputList[] = $e; } else if (inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $s = $e; } $cp1 = $cp2; } return $outputList; } $subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]]; $clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]]; $clippedPolygon = clip($subjectPolygon, $clipPolygon); echo json_encode($clippedPolygon); echo "\n"; ?>
package main import "fmt" type point struct { x, y float32 } var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}} var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}} func main() { var cp1, cp2, s, e point inside := func(p point) bool { return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) } intersection := func() (p point) { dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y dpx, dpy := s.x-e.x, s.y-e.y n1 := cp1.x*cp2.y - cp1.y*cp2.x n2 := s.x*e.y - s.y*e.x n3 := 1 / (dcx*dpy - dcy*dpx) p.x = (n1*dpx - n2*dcx) * n3 p.y = (n1*dpy - n2*dcy) * n3 return } outputList := subjectPolygon cp1 = clipPolygon[len(clipPolygon)-1] for _, cp2 = range clipPolygon { inputList := outputList outputList = nil s = inputList[len(inputList)-1] for _, e = range inputList { if inside(e) { if !inside(s) { outputList = append(outputList, intersection()) } outputList = append(outputList, e) } else if inside(s) { outputList = append(outputList, intersection()) } s = e } cp1 = cp2 } fmt.Println(outputList) }
Convert the following code from PHP to Go, ensuring the logic remains intact.
$ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll"); $cstr = $ffi->_strdup("success"); $str = FFI::string($cstr); echo $str; FFI::free($cstr);
package main import "C" import ( "fmt" "unsafe" ) func main() { go1 := "hello C" c1 := C.CString(go1) go1 = "" c2 := C.strdup(c1) C.free(unsafe.Pointer(c1)) go2 := C.GoString(c2) C.free(unsafe.Pointer(c2)) fmt.Println(go2) }
Generate a Go translation of this PHP snippet without changing its computational steps.
$ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll"); $cstr = $ffi->_strdup("success"); $str = FFI::string($cstr); echo $str; FFI::free($cstr);
package main import "C" import ( "fmt" "unsafe" ) func main() { go1 := "hello C" c1 := C.CString(go1) go1 = "" c2 := C.strdup(c1) C.free(unsafe.Pointer(c1)) go2 := C.GoString(c2) C.free(unsafe.Pointer(c2)) fmt.Println(go2) }
Ensure the translated Go code behaves exactly like the original PHP snippet.
<?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); ?>
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) }
Write a version of this PHP function in Go with identical behavior.
<?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); ?>
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) }
Convert this PHP snippet to Go and keep its semantics consistent.
<?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); ?>
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) }
Change the programming language of this snippet from PHP to Go without modifying what it does.
<?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); ?>
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) }
Maintain the same structure and functionality when rewriting this code in Go.
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }
Change the following PHP code into Go without altering its purpose.
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }
Translate the given PHP code snippet into Go without altering its behavior.
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }
Write the same algorithm in Go as shown in this PHP implementation.
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }
Maintain the same structure and functionality when rewriting this code in Go.
$arr1 = array(1, 2, 3); $arr2 = array(4, 5, 6); $arr3 = array_merge($arr1, $arr2);
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) }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
$arr1 = array(1, 2, 3); $arr2 = array(4, 5, 6); $arr3 = array_merge($arr1, $arr2);
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) }
Ensure the translated Go code behaves exactly like the original PHP snippet.
#!/usr/bin/php <?php $string = fgets(STDIN); $integer = (int) fgets(STDIN);
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") } }
Write the same code in Go as shown below in PHP.
#!/usr/bin/php <?php $string = fgets(STDIN); $integer = (int) fgets(STDIN);
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") } }
Convert this PHP block to Go, preserving its control flow and logic.
######################################################### # 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>";
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 }
Produce a language-to-language conversion: from PHP to Go, same semantics.
######################################################### # 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>";
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 }
Translate this program into Go but keep the logic exactly as in PHP.
$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; }
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)) } }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
$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; }
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)) } }
Port the following code from PHP to Go with equivalent syntax and logic.
<?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";
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) } }
Please provide an equivalent version of this PHP code in Go.
<?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";
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) } }
Rewrite this program in Go while keeping its functionality equivalent to the PHP version.
$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";
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) }
Write the same algorithm in Go as shown in this PHP implementation.
$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";
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) }
Produce a language-to-language conversion: from PHP to Go, same semantics.
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
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) }
Convert the following code from PHP to Go, ensuring the logic remains intact.
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
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) }
Produce a functionally identical Go code for the snippet given in PHP.
<?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); ?>
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) } }
Generate an equivalent Go version of this PHP code.
<?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); ?>
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) } }
Write the same algorithm in Go as shown in this PHP implementation.
<?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)); }
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) } }
Keep all operations the same but rewrite the snippet in Go.
<?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)); }
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) } }
Ensure the translated Go code behaves exactly like the original PHP snippet.
<?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)); }
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) } }
Convert the following code from PHP to Go, ensuring the logic remains intact.
<?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)); }
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) } }
Produce a language-to-language conversion: from PHP to Go, same semantics.
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 ]; } }
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 }
Preserve the algorithm and functionality while converting the code from PHP to Go.
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 ]; } }
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 }
Ensure the translated Go code behaves exactly like the original PHP snippet.
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
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)) }
Change the programming language of this snippet from PHP to Go without modifying what it does.
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
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)) }
Write the same code in Go as shown below in PHP.
<?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; }
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) } }
Write the same code in Go as shown below in PHP.
<?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; }
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) } }
Maintain the same structure and functionality when rewriting this code in Go.
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; }
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) }
Generate a Go translation of this PHP snippet without changing its computational steps.
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; }
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) }
Keep all operations the same but rewrite the snippet in Go.
<?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!"); } ?>
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) }
Produce a functionally identical Go code for the snippet given in PHP.
<?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!"); } ?>
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) }
Transform the following PHP implementation into Go, maintaining the same output and logic.
<?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 ?>
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]) }
Generate a Go translation of this PHP snippet without changing its computational steps.
<?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 ?>
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]) }
Keep all operations the same but rewrite the snippet in Go.
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
func isLeap(year int) bool { return year%400 == 0 || year%4 == 0 && year%100 != 0 }
Write the same code in Go as shown below in PHP.
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
func isLeap(year int) bool { return year%400 == 0 || year%4 == 0 && year%100 != 0 }
Please provide an equivalent version of this PHP code in Go.
$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]}"; }
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 }
Produce a language-to-language conversion: from PHP to Go, same semantics.
$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]}"; }
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 }
Write a version of this PHP function in Go with identical behavior.
<?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>
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) } }
Maintain the same structure and functionality when rewriting this code in Go.
<?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>
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) } }
Translate the given PHP code snippet into Go without altering its behavior.
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; }
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) }
Write the same algorithm in Go as shown in this PHP implementation.
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $arr; }
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) }
Maintain the same structure and functionality when rewriting this code in Go.
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
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] }
Ensure the translated Go code behaves exactly like the original PHP snippet.
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
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] }
Write the same code in Go as shown below in PHP.
$s = "12345"; $s++;
package main import "fmt" import "strconv" func main() { i, _ := strconv.Atoi("1234") fmt.Println(strconv.Itoa(i + 1)) }
Maintain the same structure and functionality when rewriting this code in Go.
$s = "12345"; $s++;
package main import "fmt" import "strconv" func main() { i, _ := strconv.Atoi("1234") fmt.Println(strconv.Itoa(i + 1)) }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
<?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"; ?>
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")) }
Please provide an equivalent version of this PHP code in Go.
<?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"; ?>
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")) }
Rewrite the snippet below in Go so it works the same as the original PHP code.
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) - 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);
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 }
Convert this PHP block to Go, preserving its control flow and logic.
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);
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 }
Port the provided PHP code into Go while preserving the original functionality.
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
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") } } }
Maintain the same structure and functionality when rewriting this code in Go.
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
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") } } }
Translate the given PHP code snippet into Go without altering its behavior.
<?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) ); }
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 }
Keep all operations the same but rewrite the snippet in Go.
<?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) ); }
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 }
Keep all operations the same but rewrite the snippet in Go.
<?php echo "Hello world!\n"; ?>
package main import "fmt" func main() { fmt.Println("Hello world!") }