WeixiangYan/CodeTransOcean huggingface dataset:
Task: Rock-paper-scissors




Go: package main

import (
    "fmt"
    "math/rand"
    "strings"
    "time"
)

const rps = "rps"

var msg = []string{
    "Rock breaks scissors",
    "Paper covers rock",
    "Scissors cut paper",
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println("Rock Paper Scissors")
    fmt.Println("Enter r, p, or s as your play.  Anything else ends the game.")
    fmt.Println("Running score shown as <your wins>:<my wins>")
    var pi string 
    var aScore, pScore int
    sl := 3               
    pcf := make([]int, 3) 
    var plays int
    aChoice := rand.Intn(3) 
    for {
        
        fmt.Print("Play: ")
        _, err := fmt.Scanln(&pi)  
        if err != nil || len(pi) != 1 {
            break
        }
        pChoice := strings.Index(rps, pi)
        if pChoice < 0 {
            break
        }
        pcf[pChoice]++
        plays++

        
        fmt.Printf("My play:%s%c.  ", strings.Repeat(" ", sl-2), rps[aChoice])
        switch (aChoice - pChoice + 3) % 3 {
        case 0:
            fmt.Println("Tie.")
        case 1:
            fmt.Printf("%s.  My point.\n", msg[aChoice])
            aScore++
        case 2:
            fmt.Printf("%s.  Your point.\n", msg[pChoice])
            pScore++
        }

        
        sl, _ = fmt.Printf("%d:%d  ", pScore, aScore)

        
        switch rn := rand.Intn(plays); {
        case rn < pcf[0]:
            aChoice = 1
        case rn < pcf[0]+pcf[1]:
            aChoice = 2
        default:
            aChoice = 0
        }
    }
}



PHP: <?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";

$player = strtoupper( $_GET["moves"] );
$wins = [
    'ROCK' => 'SCISSORS',
    'PAPER' => 'ROCK',
    'SCISSORS' => 'PAPER'
  ];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>";
echo "<br>";
echo "<br>" . "A.I chooses " . "<i style=\"color:red\">"  . $a_i . "</i>";

$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
  $results = "A.I wins";
} else {
  $results = "Player wins";
}

echo "<br>" . $results;
?>
Task: Y combinator




Go: package main

import "fmt"

type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func

func main() {
	fac := Y(almost_fac)
	fib := Y(almost_fib)
	fmt.Println("fac(10) = ", fac(10))
	fmt.Println("fib(10) = ", fib(10))
}

func Y(f FuncFunc) Func {
	g := func(r RecursiveFunc) Func {
		return f(func(x int) int {
			return r(r)(x)
		})
	}
	return g(g)
}

func almost_fac(f Func) Func {
	return func(x int) int {
		if x <= 1 {
			return 1
		}
		return x * f(x-1)
	}
}

func almost_fib(f Func) Func {
	return func(x int) int {
		if x <= 2 {
			return 1
		}
		return f(x-1)+f(x-2)
	}
}



PHP: <?php
function Y($f) {
  $g = function($w) use($f) {
    return $f(function() use($w) {
      return call_user_func_array($w($w), func_get_args());
    });
  };
  return $g($g);
}

$fibonacci = Y(function($f) {
  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});

echo $fibonacci(10), "\n";

$factorial = Y(function($f) {
  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});

echo $factorial(10), "\n";
?>
Task: Return multiple values




Go: func addsub(x, y int) (int, int) {
  return x + y, x - y
}



PHP: function addsub($x, $y) {
  return array($x + $y, $x - $y);
}
Task: FTP




Go: package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"github.com/stacktic/ftp"
)

func main() {
	
	const (
		hostport = "localhost:21"
		username = "anonymous"
		password = "anonymous"
		dir      = "pub"
		file     = "somefile.bin"
	)

	conn, err := ftp.Connect(hostport)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Quit()
	fmt.Println(conn)

	if err = conn.Login(username, password); err != nil {
		log.Fatal(err)
	}
	if err = conn.ChangeDir(dir); err != nil {
		log.Fatal(err)
	}
	fmt.Println(conn.CurrentDir())
	files, err := conn.List(".")
	if err != nil {
		log.Fatal(err)
	}
	for _, f := range files {
		fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
	}

	r, err := conn.Retr(file)
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	f, err := os.Create(file)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	n, err := io.Copy(f, r)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Wrote", n, "bytes to", file)
}



PHP: $server = "speedtest.tele2.net";
$user = "anonymous";
$pass = "ftptest@example.com";

$conn = ftp_connect($server);
if (!$conn) {
    die('unable to connect to: '. $server);
}
$login = ftp_login($conn, $user, $pass);
if (!$login) {
    echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;
} else{
    echo 'connected successfully'.PHP_EOL;
    $directory = ftp_nlist($conn,'');
    print_r($directory);
}
if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {
    echo "Successfully downloaded file".PHP_EOL;
} else {
    echo "failed to download file";
}
Task: Loops_Continue




Go: package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        fmt.Printf("%d", i)
        if i%5 == 0 {
            fmt.Printf("\n")
            continue
        }
        fmt.Printf(", ")
    }
}



PHP: for ($i = 1; $i <= 10; $i++) {
    echo $i;
    if ($i % 5 == 0) {
        echo "\n";
        continue;
    }
    echo ', ';
}
Task: Colour bars_Display




Go: package main

import "github.com/fogleman/gg"

var colors = [8]string{
    "000000", 
    "FF0000", 
    "00FF00", 
    "0000FF", 
    "FF00FF", 
    "00FFFF", 
    "FFFF00", 
    "FFFFFF", 
}

func drawBars(dc *gg.Context) {
    w := float64(dc.Width() / len(colors))
    h := float64(dc.Height())
    for i := range colors {
        dc.SetHexColor(colors[i])
        dc.DrawRectangle(w*float64(i), 0, w, h)
        dc.Fill()
    }
}

func main() {
    dc := gg.NewContext(400, 400)
    drawBars(dc)
    dc.SavePNG("color_bars.png")
}



PHP: <?php
$colors = array(array(  0,   0,   0),   // black
                array(255,   0,   0),   // red
                array(  0, 255,   0),   // green
                array(  0,   0, 255),   // blue
                array(255,   0, 255),   // magenta
                array(  0, 255, 255),   // cyan
                array(255, 255,   0),   // yellow
                array(255, 255, 255));  // white

define('BARWIDTH', 640 / count($colors));
define('HEIGHT',   480);

$image = imagecreate(BARWIDTH * count($colors), HEIGHT);

foreach ($colors as $position => $color) {
    $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
    imagefilledrectangle($image, $position * BARWIDTH, 0,
                         $position * BARWIDTH + BARWIDTH - 1,
                         HEIGHT - 1, $color);
}

header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
Task: General FizzBuzz




Go: package main

import (
	"fmt"
)

const numbers = 3

func main() {

	
	max := 20
	words := map[int]string{
		3: "Fizz",
		5: "Buzz",
		7: "Baxx",
	}
	keys := []int{3, 5, 7}
	divisible := false
	for i := 1; i <= max; i++ {
		for _, n := range keys {
			if i % n == 0 {
				fmt.Print(words[n])
				divisible = true
			}
		}
		if !divisible {
			fmt.Print(i)
		}
		fmt.Println()
		divisible = false
	}

}



PHP: <?php

$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');

for ($i = 1 ; $i <= $max ; $i++) {
    $matched = false;
    foreach ($factor AS $number => $word) {
        if ($i % $number == 0) {
            echo $word;
            $matched = true;
        }
    }
    echo ($matched ? '' : $i), PHP_EOL;
}

?>
Task: Read a specific line from a file




Go: package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
)

func main() {
	if line, err := rsl("input.txt", 7); err == nil {
		fmt.Println("7th line:")
		fmt.Println(line)
	} else {
		fmt.Println("rsl:", err)
	}
}

func rsl(fn string, n int) (string, error) {
	if n < 1 {
		return "", fmt.Errorf("invalid request: line %d", n)
	}
	f, err := os.Open(fn)
	if err != nil {
		return "", err
	}
	defer f.Close()
	bf := bufio.NewReader(f)
	var line string
	for lnum := 0; lnum < n; lnum++ {
		line, err = bf.ReadString('\n')
		if err == io.EOF {
			switch lnum {
			case 0:
				return "", errors.New("no lines in file")
			case 1:
				return "", errors.New("only 1 line")
			default:
				return "", fmt.Errorf("only %d lines", lnum)
			}
		}
		if err != nil {
			return "", err
		}
	}
	if line == "" {
		return "", fmt.Errorf("line %d empty", n)
	}
	return line, nil
}



PHP: <?php  
  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];
  
  function fileLine ($lineNum, $file) {
    $count = 0;
    while (!feof($file)) {
      $count++;
      $line = fgets($file);
      if ($count == $lineNum) return $line;
    }
    die("Requested file has fewer than ".$lineNum." lines!");
  }
    
  @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
  if (!$fp) die("Input file not found!");
  echo fileLine(7, $fp);
?>
Task: File extension is in extensions list




Go: package main

import (
    "fmt"
    "strings"
)

var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}

func fileExtInList(filename string) (bool, string) {
    filename2 := strings.ToLower(filename)
    for _, ext := range extensions {
        ext2 := "." + strings.ToLower(ext)
        if strings.HasSuffix(filename2, ext2) {
            return true, ext
        }
    }
    s := strings.Split(filename, ".")
    if len(s) > 1 {
        t := s[len(s)-1]
        if t != "" {
            return false, t
        } else {
            return false, "<empty>"
        }
    } else {
        return false, "<none>"
    }
}

func main() {
    fmt.Println("The listed extensions are:")
    fmt.Println(extensions, "\n")
    tests := []string{
        "MyData.a##", "MyData.tar.Gz", "MyData.gzip",
        "MyData.7z.backup", "MyData...", "MyData",
        "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2",
    }
    for _, test := range tests {
        ok, ext := fileExtInList(test)
        fmt.Printf("%-20s => %-5t  (extension = %s)\n", test, ok, ext)
    }
}



PHP: $allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
$lc_allowed = array_map('strtolower', $allowed);

$tests = [
    ['MyData.a##',true],
    ['MyData.tar.Gz',true],
    ['MyData.gzip',false],
    ['MyData.7z.backup',false],
    ['MyData...',false],
    ['MyData',false],
    ['archive.tar.gz', true]
];

foreach ($tests as $test) {
    $ext = pathinfo($test[0], PATHINFO_EXTENSION);
    if (in_array(strtolower($ext), $lc_allowed)) {
        $result = 'true';
    } else {
        $result = 'false';
    }
    printf("%20s : %s \n", $test[0],$result);
}
Task: String case




Go: package main

import (
    "fmt"
    "strings"
    "unicode"
    "unicode/utf8"
)

func main() {
    show("alphaBETA")
    show("alpha BETA")
    
    show("Ǆǈǌ")
    
    show("o'hare O'HARE o’hare don't")
}

func show(s string) {
    fmt.Println("\nstring:         ",
        s, " len:", utf8.RuneCountInString(s), "runes") 
    fmt.Println("All upper case: ", strings.ToUpper(s)) 
    fmt.Println("All lower case: ", strings.ToLower(s)) 
    fmt.Println("All title case: ", strings.ToTitle(s)) 
    fmt.Println("Title words:    ", strings.Title(s))   
    fmt.Println("Swapping case:  ",                     
        strings.Map(unicode.SimpleFold, s))
}



PHP: $str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta

echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
Task: MD5




Go: package main

import (
    "crypto/md5"
    "fmt"
)

func main() {
    for _, p := range [][2]string{
        
        {"d41d8cd98f00b204e9800998ecf8427e", ""},
        {"0cc175b9c0f1b6a831c399e269772661", "a"},
        {"900150983cd24fb0d6963f7d28e17f72", "abc"},
        {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
        {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
        {"d174ab98d277d9f5a5611c2c9f419d9f",
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
        {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
            "123456789012345678901234567890123456789012345678901234567890"},
        
        {"e38ca1d920c4b8b8d3946b2c72f01680",
            "The quick brown fox jumped over the lazy dog's back"},
    } {
        validate(p[0], p[1])
    }
}

var h = md5.New()

func validate(check, s string) {
    h.Reset()
    h.Write([]byte(s))
    sum := fmt.Sprintf("%x", h.Sum(nil))
    if sum != check {
        fmt.Println("MD5 fail")
        fmt.Println("  for string,", s)
        fmt.Println("  expected:  ", check)
        fmt.Println("  got:       ", sum)
    }
}



PHP: $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );
Task: Date manipulation




Go: package main

import (
    "fmt"
    "time"
)

const taskDate = "March 7 2009 7:30pm EST"
const taskFormat = "January 2 2006 3:04pm MST"

func main() {
    if etz, err := time.LoadLocation("US/Eastern"); err == nil {
        time.Local = etz
    }
    fmt.Println("Input:             ", taskDate)
    t, err := time.Parse(taskFormat, taskDate)
    if err != nil {
        fmt.Println(err)
        return
    }
    t = t.Add(12 * time.Hour)
    fmt.Println("+12 hrs:           ", t)
    if _, offset := t.Zone(); offset == 0 {
        fmt.Println("No time zone info.")
        return
    }
    atz, err := time.LoadLocation("US/Arizona")
    if err == nil {
        fmt.Println("+12 hrs in Arizona:", t.In(atz))
    }
}



PHP: <?php
$time = new DateTime('March 7 2009 7:30pm EST');
$time->modify('+12 hours');
echo $time->format('c');
?>
Task: Sorting algorithms_Sleep sort




Go: package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"
)

func main() {
	out := make(chan uint64)
	for _, a := range os.Args[1:] {
		i, err := strconv.ParseUint(a, 10, 64)
		if err != nil {
			log.Fatal(err)
		}
		go func(n uint64) {
			time.Sleep(time.Duration(n) * time.Millisecond)
			out <- n
		}(i)
	}
	for _ = range os.Args[1:] {
		fmt.Println(<-out)
	}
}



PHP: <?php

$buffer = 1;
$pids = [];

for ($i = 1; $i < $argc; $i++) {
    $pid = pcntl_fork();
    if ($pid < 0) {
        die("failed to start child process");
    }

    if ($pid === 0) {
        sleep($argv[$i] + $buffer);
        echo $argv[$i] . "\n";
        exit();
    }
    
    $pids[] = $pid;
}

foreach ($pids as $pid) {
    pcntl_waitpid($pid, $status);
}
Task: Loops_Nested




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())

    values := make([][]int, 10)
    for i := range values {
        values[i] = make([]int, 10)
        for j := range values[i] {
            values[i][j] = rand.Intn(20) + 1
        }
    }

outerLoop:
    for i, row := range values {
        fmt.Printf("%3d)", i)
        for _, value := range row {
            fmt.Printf(" %3d", value)
            if value == 20 {
                break outerLoop
            }
        }
        fmt.Printf("\n")
    }
    fmt.Printf("\n")
}



PHP: <?php
for ($i = 0; $i < 10; $i++)
    for ($j = 0; $j < 10; $j++)
        $a[$i][$j] = rand(1, 20);

foreach ($a as $row) {
    foreach ($row as $element) {
        echo " $element";
        if ($element == 20)
            break 2; // 2 is the number of loops we want to break out of
    }
    echo "\n";
}
echo "\n";
?>
Task: Pythagorean triples




Go: package main

import "fmt"

var total, prim, maxPeri int64

func newTri(s0, s1, s2 int64) {
    if p := s0 + s1 + s2; p <= maxPeri {
        prim++
        total += maxPeri / p
        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)
        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)
        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
    }
}

func main() {
    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {
        prim = 0
        total = 0
        newTri(3, 4, 5)
        fmt.Printf("Up to %d:  %d triples, %d primitives\n",
            maxPeri, total, prim)
    }
}



PHP: <?php
 
function gcd($a, $b)
{
    if ($a == 0)
       return $b;
    if ($b == 0)
       return $a;
    if($a == $b)
        return $a;
    if($a > $b)
        return gcd($a-$b, $b);
    return gcd($a, $b-$a);
}

$pytha = 0;
$prim = 0;
$max_p = 100;

for ($a = 1; $a <= $max_p / 3; $a++) {
    $aa = $a**2;
    for ($b = $a + 1; $b < $max_p/2; $b++) {
        $bb = $b**2;
        for ($c = $b + 1; $c < $max_p/2; $c++) {
            $cc = $c**2;
            if ($aa + $bb < $cc) break;
            if ($a + $b + $c > $max_p) break;

            if ($aa + $bb == $cc) {
                $pytha++;
                if (gcd($a, $b) == 1) $prim++;
            }
        }
    }
}

echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Task: Remove duplicate elements




Go: package main

import "fmt"

func uniq(list []int) []int {
	unique_set := make(map[int]bool, len(list))
	for _, x := range list {
		unique_set[x] = true
	}
	result := make([]int, 0, len(unique_set))
	for x := range unique_set {
		result = append(result, x)
	}
	return result
}

func main() {
	fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) 
}



PHP: $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);
Task: Look-and-say sequence




Go: package main

import (
    "fmt"
    "strconv"
)

func lss(s string) (r string) {
    c := s[0]
    nc := 1
    for i := 1; i < len(s); i++ {
        d := s[i]
        if d == c {
            nc++
            continue
        }
        r += strconv.Itoa(nc) + string(c)
        c = d
        nc = 1
    }
    return r + strconv.Itoa(nc) + string(c)
}

func main() {
    s := "1"
    fmt.Println(s)
    for i := 0; i < 8; i++ {
        s = lss(s)
        fmt.Println(s)
    }
}



PHP: <?php

function lookAndSay($str) {

	return preg_replace_callback('#(.)\1*#', function($matches) {
	
		return strlen($matches[0]).$matches[1];
	}, $str);
}

$num = "1";

foreach(range(1,10) as $i) {

	echo $num."<br/>";
	$num = lookAndSay($num);
}

?>
Task: Stack




Go: var intStack []int



PHP: $stack = array();

empty( $stack ); // true

array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;

empty( $stack ); // false

echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"
Task: Conditional structures




Go: if booleanExpression {
    statements
}



PHP: <?php

$foo = 3;

if ($foo == 2)


if ($foo == 3)

else


if ($foo != 0)
{

}
else
{

}

?>
Task: Sorting algorithms_Stooge sort




Go: package main

import "fmt"

var a = []int{170, 45, 75, -90, -802, 24, 2, 66}

func main() {
    fmt.Println("before:", a)
    stoogesort(a)
    fmt.Println("after: ", a)
    fmt.Println("nyuk nyuk nyuk")
}

func stoogesort(a []int) {
    last := len(a) - 1
    if a[last] < a[0] {
        a[0], a[last] = a[last], a[0]
    }
    if last > 1 {
        t := len(a) / 3
        stoogesort(a[:len(a)-t])
        stoogesort(a[t:])
        stoogesort(a[:len(a)-t])
    }
}



PHP: function stoogeSort(&$arr, $i, $j)
{
	if($arr[$j] < $arr[$i])
	{
		list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
	}
	if(($j - $i) > 1)
	{
		$t = ($j - $i + 1) / 3;
		stoogesort($arr, $i, $j - $t);
		stoogesort($arr, $i + $t, $j);
		stoogesort($arr, $i, $j - $t);
	}
}
Task: Sort using a custom comparator




Go: package main

import (
    "fmt"
    "sort"
    "strings"
)

type sortable []string

func (s sortable) Len() int      { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
    a, b := s[i], s[j]
    if len(a) != len(b) {
        return len(a) > len(b)
    }
    return strings.ToLower(a) < strings.ToLower(b)
}

func main() {
    var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
    fmt.Println(s, "(original)")

    sort.Sort(s)
    fmt.Println(s, "(sorted)")
}



PHP: <?php
function mycmp($s1, $s2)
{
    if ($d = strlen($s2) - strlen($s1))
        return $d;
    return strcasecmp($s1, $s2);
}

$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>
Task: Sorting algorithms_Selection sort




Go: package main

import "fmt"

var a = []int{170, 45, 75, -90, -802, 24, 2, 66}

func main() {
    fmt.Println("before:", a)
    selectionSort(a)
    fmt.Println("after: ", a)
}

func selectionSort(a []int) {
    last := len(a) - 1
    for i := 0; i < last; i++ {
        aMin := a[i]
        iMin := i
        for j := i + 1; j < len(a); j++ {
            if a[j] < aMin {
                aMin = a[j]
                iMin = j
            }
        }
        a[i], a[iMin] = aMin, a[i]
    }
}



PHP: function selection_sort(&$arr) {
    $n = count($arr);
    for($i = 0; $i < count($arr); $i++) {
        $min = $i;
        for($j = $i + 1; $j < $n; $j++){
            if($arr[$j] < $arr[$min]){
                $min = $j;
            }
        }
        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
    }
}
Task: Apply a callback to an array




Go: package main

import "fmt"

func main() {
    for _, i := range []int{1, 2, 3, 4, 5} {
        fmt.Println(i * i)
    }
}



PHP: function cube($n)
{
   return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
Task: Singleton




Go: package main

import (
    "log"
    "math/rand"
    "sync"
    "time"
)

var (
    instance string
    once     sync.Once 
)

func claim(color string, w *sync.WaitGroup) {
    time.Sleep(time.Duration(rand.Intn(1e8))) 
    log.Println("trying to claim", color)
    once.Do(func() { instance = color })
    log.Printf("tried %s. instance: %s", color, instance)
    w.Done()
}

func main() {
    rand.Seed(time.Now().Unix())
    var w sync.WaitGroup
    w.Add(2)
    go claim("red", &w) 
    go claim("blue", &w)
    w.Wait()
    log.Println("after trying both, instance =", instance)
}



PHP: class Singleton {
  protected static $instance = null;
  public $test_var;
  private function __construct(){

  }
  public static function getInstance(){
    if (is_null(self::$instance)){
      self::$instance = new self();
    }
    return self::$instance;
  }
}

$foo = Singleton::getInstance();
$foo->test_var = 'One';

$bar = Singleton::getInstance();
echo $bar->test_var; //Prints 'One'

$fail = new Singleton(); //Fatal error
Task: Case-sensitivity of identifiers




Go: package dogs

import "fmt"



var dog = "Salt"
var Dog = "Pepper"
var DOG = "Mustard"

func PackageSees() map[*string]int {
    
    fmt.Println("Package sees:", dog, Dog, DOG)
    
    
    
    
    return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}
}



PHP: <?php



$dog = 'Benjamin';
$Dog = 'Samba';
$DOG = 'Bernie';

echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n";


function DOG() { return 'Bernie'; }

echo 'There is only 1 dog named ' . dog() . "\n";
Task: Loops_Downward for




Go: for i := 10; i >= 0; i-- {
  fmt.Println(i)
}



PHP: for ($i = 10; $i >= 0; $i--)
  echo "$i\n";
Task: Write entire file




Go: import "io/ioutil"

func main() {
    ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}



PHP: file_put_contents($filename, $data)
Task: Loops_For




Go: package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        for j := 1; j <= i; j++ {
            fmt.Printf("*")
        }
        fmt.Printf("\n")
    }
}



PHP: for ($i = 1; $i <= 5; $i++) {
  for ($j = 1; $j <= $i; $j++) {
    echo '*';
  }
  echo "\n";
}