WeixiangYan/CodeTransOcean huggingface dataset:
Task: Long year




Go: package main

import (
    "fmt"
    "time"
)

func main() {
    centuries := []string{"20th", "21st", "22nd"}
    starts := []int{1900, 2000, 2100} 
    for i := 0; i < len(centuries); i++ {
        var longYears []int
        fmt.Printf("\nLong years in the %s century:\n", centuries[i])
        for j := starts[i]; j < starts[i] + 100; j++ {
            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
            if _, week := t.ISOWeek(); week == 53 {
                longYears = append(longYears, j)
            }
        }
        fmt.Println(longYears)
    }
}



PHP: function isLongYear($year) {
  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}

for ($y=1995; $y<=2045; ++$y) {
  if (isLongYear($y)) {
    printf("%s\n", $y);
  }
}
Task: Associative array_Merging




Go: package main

import "fmt"

type assoc map[string]interface{}

func merge(base, update assoc) assoc {
    result := make(assoc)
    for k, v := range base {
        result[k] = v
    }
    for k, v := range update {
        result[k] = v
    }
    return result
}

func main() {
    base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
    update := assoc{"price": 15.25, "color": "red", "year": 1974}
    result := merge(base, update)
    fmt.Println(result)
}



PHP: <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);

$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
Task: Associative array_Iteration




Go: myMap := map[string]int {
	   "hello": 13,
	   "world": 31,
	   "!"    : 71 }


for key, value := range myMap {
    fmt.Printf("key = %s, value = %d\n", key, value)
}


for key := range myMap {
    fmt.Printf("key = %s\n", key)
}


for _, value := range myMap {
    fmt.Printf("value = %d\n", value)
}



PHP: <?php
$pairs = array( "hello" => 1,
		"world" => 2,
		"!"     => 3 );

foreach($pairs as $k => $v) {
  echo "(k,v) = ($k, $v)\n";
}

foreach(array_keys($pairs) as $key) {
  echo "key = $key, value = $pairs[$key]\n";
}

foreach($pairs as $value) {
  echo "values = $value\n";
}
?>
Task: Here document




Go: var m = `    leading spaces

and blank lines`



PHP: $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
Task: Hash join




Go: package main

import "fmt"

func main() {
    tableA := []struct {
        value int
        key   string
    }{
        {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
        {28, "Alan"},
    }
    tableB := []struct {
        key   string
        value string
    }{
        {"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
    }
    
    h := map[string][]int{}
    for i, r := range tableA {
        h[r.key] = append(h[r.key], i)
    }
    
    for _, x := range tableB {
        for _, a := range h[x.key] {
            fmt.Println(tableA[a], x)
        }
    }
}



PHP: <?php
function hashJoin($table1, $index1, $table2, $index2) {

    foreach ($table1 as $s)
        $h[$s[$index1]][] = $s;

    foreach ($table2 as $r)
    	foreach ($h[$r[$index2]] as $s)
	    $result[] = array($s, $r);
    return $result;
}

$table1 = array(array(27, "Jonah"),
           array(18, "Alan"),
           array(28, "Glory"),
           array(18, "Popeye"),
           array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
           array("Jonah", "Spiders"),
           array("Alan", "Ghosts"),
           array("Alan", "Zombies"),
           array("Glory", "Buffy"),
           array("Bob", "foo"));

foreach (hashJoin($table1, 1, $table2, 0) as $row)
    print_r($row);
?>
Task: Respond to an unknown method call




Go: package main

import (
    "fmt"
    "reflect"
)

type example struct{}

func (example) Foo() int {
    return 42
}


func (e example) CallMethod(n string) int {
    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {
        
        return int(m.Call(nil)[0].Int())
    }
    
    fmt.Println("Unknown method:", n)
    return 0
}

func main() {
    var e example
    fmt.Println(e.CallMethod("Foo"))
    fmt.Println(e.CallMethod("Bar"))
}



PHP: <?php
class Example {
  function foo() {
    echo "this is foo\n";
  }
  function bar() {
    echo "this is bar\n";
  }
  function __call($name, $args) {
    echo "tried to handle unknown method $name\n";
    if ($args)
      echo "it had arguments: ", implode(', ', $args), "\n";
  }
}

$example = new Example();

$example->foo();        // prints "this is foo"
$example->bar();        // prints "this is bar"
$example->grill();      // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"

?>
Task: Inheritance_Single




Go: package main

type animal struct {
    alive bool
}

type dog struct {
    animal
    obedienceTrained bool
}

type cat struct {
    animal
    litterBoxTrained bool
}

type lab struct {
    dog
    color string
}

type collie struct {
    dog
    catchesFrisbee bool
}

func main() {
    var pet lab
    pet.alive = true
    pet.obedienceTrained = false
    pet.color = "yellow"
}



PHP: class Animal {

}

class Dog extends Animal {

}

class Cat extends Animal {

}

class Lab extends Dog {

}

class Collie extends Dog {

}
Task: Associative array_Creation




Go: 
var x map[string]int


x = make(map[string]int)


x = make(map[string]int, 42)


x["foo"] = 3


y1 := x["bar"]     
y2, ok := x["bar"] 


delete(x, "foo")


x = map[string]int{
	"foo": 2, "bar": 42, "baz": -1,
}



PHP: $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';

echo($array['foo']); // bar
echo($array['moo']); // Undefined index

$array2 = array('fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green');

$array2 = ['fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green'];

echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
Task: Polymorphism




Go: package main

import "fmt"

type point struct {
    x, y float64
}

type circle struct {
    x, y, r float64
}

type printer interface {
    print()
}

func (p *point) print() {
    fmt.Println(p.x, p.y)
}

func (c *circle) print() {
    fmt.Println(c.x, c.y, c.r)
}

func main() {
    var i printer            
    i = newPoint(3, 4)       
    i.print()                
    i = newCircle(5, 12, 13) 
    i.print()                
}












func (p *point) getX() float64  { return p.x }
func (p *point) getY() float64  { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }

func (c *circle) getX() float64  { return c.x }
func (c *circle) getY() float64  { return c.y }
func (c *circle) getR() float64  { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }



func (p *point) clone() *point   { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }


func (p *point) set(q *point)   { *p = *q }
func (c *circle) set(d *circle) { *c = *d }










func newPoint(x, y float64) *point {
    return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
    return &circle{x, y, r}
}





PHP: class Point
{
  protected $_x;

  protected $_y;
  
  public function __construct()
  {
    switch( func_num_args() )
    {
      case 1:
        $point = func_get_arg( 0 );
        $this->setFromPoint( $point );
        break;
      case 2:
        $x = func_get_arg( 0 );
        $y = func_get_arg( 1 );
        $this->setX( $x );
        $this->setY( $y );
        break;
      default:
        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
    }
  }
  
  public function setFromPoint( Point $point )
  {
    $this->setX( $point->getX() );
    $this->setY( $point->getY() );
  }
  
  public function getX()
  {
    return $this->_x;
  }
  
  public function setX( $x )
  {
    if( !is_numeric( $x ) )
    {
      throw new InvalidArgumentException( 'expecting numeric value' );
    }
    
    $this->_x = (float) $x;
  }
  
  public function getY()
  {
    return $this->_y;
  }
  
  public function setY( $y )
  {
    if( !is_numeric( $y ) )
    {
      throw new InvalidArgumentException( 'expecting numeric value' );
    }
    
    $this->_y = (float) $y;
  }
  
  public function output()
  {
    echo $this->__toString();
  }
  
  public function __toString()
  {
    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
  }
}
Task: Reflection_List properties




Go: package main

import (
	"fmt"
	"image"
	"reflect"
)


type t struct {
	X    int
	next *t
}

func main() {
	report(t{})
	report(image.Point{})
}

func report(x interface{}) {
	t := reflect.TypeOf(x)
	n := t.NumField()
	fmt.Printf("Type %v has %d fields:\n", t, n)
	fmt.Println("Name     Type     Exported")
	for i := 0; i < n; i++ {
		f := t.Field(i)
		fmt.Printf("%-8s %-8v %-8t\n",
			f.Name,
			f.Type,
			f.PkgPath == "",
		)
	}
	fmt.Println()
}



PHP: <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;

var_dump(get_object_vars($obj));
?>
Task: Align columns




Go: package main

import (
    "fmt"
    "strings"
)

const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.`

type formatter struct {
    text  [][]string
    width []int
}

func newFormatter(text string) *formatter {
    var f formatter
    for _, line := range strings.Split(text, "\n") {
        words := strings.Split(line, "$")
        for words[len(words)-1] == "" {
            words = words[:len(words)-1]
        }
        f.text = append(f.text, words)
        for i, word := range words {
            if i == len(f.width) {
                f.width = append(f.width, len(word))
            } else if len(word) > f.width[i] {
                f.width[i] = len(word)
            }
        }
    }
    return &f
}

const (
    left = iota
    middle
    right
)

func (f formatter) print(j int) {
    for _, line := range f.text {
        for i, word := range line {
            fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s",
                len(word)+(f.width[i]-len(word))*j/2, word))
        }
        fmt.Println("")
    }
    fmt.Println("")
}

func main() {
    f := newFormatter(text)
    f.print(left)
    f.print(middle)
    f.print(right)
}



PHP: <?php
$j2justtype = array('L' => STR_PAD_RIGHT,
                    'R' => STR_PAD_LEFT,
                    'C' => STR_PAD_BOTH);
 

function aligner($str, $justification = 'L') {
  global $j2justtype;
  assert(array_key_exists($justification, $j2justtype));
  $justtype = $j2justtype[$justification];

  $fieldsbyrow = array();
  foreach (explode("\n", $str) as $line)
    $fieldsbyrow[] = explode('$', $line);
  $maxfields = max(array_map('count', $fieldsbyrow));

  foreach (range(0, $maxfields - 1) as $col) {
    $maxwidth = 0;
    foreach ($fieldsbyrow as $fields)
      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));
    foreach ($fieldsbyrow as &$fields)
      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype);
    unset($fields); // see http://bugs.php.net/29992
  }
  $result = '';
  foreach ($fieldsbyrow as $fields)
    $result .= implode(' ', $fields) . "\n";
  return $result;
}

$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.';
 
foreach (array('L', 'R', 'C') as $j)
  echo aligner($textinfile, $j);

?>
Task: URL parser




Go: package main

import (
	"fmt"
	"log"
	"net"
	"net/url"
)

func main() {
	for _, in := range []string{
		"foo:
		"urn:example:animal:ferret:nose",
		"jdbc:mysql:
		"ftp:
		"http:
		"ldap:
		"mailto:John.Doe@example.com",
		"news:comp.infosystems.www.servers.unix",
		"tel:+1-816-555-1212",
		"telnet:
		"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",

		"ssh:
		"https:
		"http:
	} {
		fmt.Println(in)
		u, err := url.Parse(in)
		if err != nil {
			log.Println(err)
			continue
		}
		if in != u.String() {
			fmt.Printf("Note: reassmebles as %q\n", u)
		}
		printURL(u)
	}
}

func printURL(u *url.URL) {
	fmt.Println("    Scheme:", u.Scheme)
	if u.Opaque != "" {
		fmt.Println("    Opaque:", u.Opaque)
	}
	if u.User != nil {
		fmt.Println("    Username:", u.User.Username())
		if pwd, ok := u.User.Password(); ok {
			fmt.Println("    Password:", pwd)
		}
	}
	if u.Host != "" {
		if host, port, err := net.SplitHostPort(u.Host); err == nil {
			fmt.Println("    Host:", host)
			fmt.Println("    Port:", port)
		} else {
			fmt.Println("    Host:", u.Host)
		}
	}
	if u.Path != "" {
		fmt.Println("    Path:", u.Path)
	}
	if u.RawQuery != "" {
		fmt.Println("    RawQuery:", u.RawQuery)
		m, err := url.ParseQuery(u.RawQuery)
		if err == nil {
			for k, v := range m {
				fmt.Printf("        Key: %q Values: %q\n", k, v)
			}
		}
	}
	if u.Fragment != "" {
		fmt.Println("    Fragment:", u.Fragment)
	}
}



PHP: <?php

$urls = array(
    'foo://example.com:8042/over/there?name=ferret#nose',
    'urn:example:animal:ferret:nose',
    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
    'ftp://ftp.is.co.za/rfc/rfc1808.txt',
    'http://www.ietf.org/rfc/rfc2396.txt#header1',
    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
    'mailto:John.Doe@example.com',
    'news:comp.infosystems.www.servers.unix',
    'tel:+1-816-555-1212',
    'telnet://192.0.2.16:80/',
    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
);

foreach ($urls AS $url) {
    $p = parse_url($url);
    echo $url, PHP_EOL;
    print_r($p);
    echo PHP_EOL;
}
Task: Dynamic variable names




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    n := 0
    for n < 1 || n > 5 {
        fmt.Print("How many integer variables do you want to create (max 5) : ")
        scanner.Scan()
        n, _ = strconv.Atoi(scanner.Text())
        check(scanner.Err())
    }
    vars := make(map[string]int)
    fmt.Println("OK, enter the variable names and their values, below")
    for i := 1; i <= n; {
        fmt.Println("\n  Variable", i)
        fmt.Print("    Name  : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if _, ok := vars[name]; ok {
            fmt.Println("  Sorry, you've already created a variable of that name, try again")
            continue
        }
        var value int
        var err error
        for {
            fmt.Print("    Value : ")
            scanner.Scan()
            value, err = strconv.Atoi(scanner.Text())
            check(scanner.Err())
            if err != nil {
                fmt.Println("  Not a valid integer, try again")
            } else {
                break
            }
        }
        vars[name] = value
        i++
    }
    fmt.Println("\nEnter q to quit")
    for {
        fmt.Print("\nWhich variable do you want to inspect : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if s := strings.ToLower(name); s == "q" {
            return
        }
        v, ok := vars[name]
        if !ok {
            fmt.Println("Sorry there's no variable of that name, try again")
        } else {
            fmt.Println("It's value is", v)
        }
    }
}



PHP: <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
Task: Reflection_List methods




Go: package main

import (
	"fmt"
	"image"
	"reflect"
)

type t int 


func (r t) Twice() t       { return r * 2 }
func (r t) Half() t        { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}

func main() {
	report(t(0))
	report(image.Point{})
}

func report(x interface{}) {
	v := reflect.ValueOf(x)
	t := reflect.TypeOf(x) 
	n := t.NumMethod()
	fmt.Printf("Type %v has %d exported methods:\n", t, n)
	const format = "%-6s %-46s %s\n"
	fmt.Printf(format, "Name", "Method expression", "Method value")
	for i := 0; i < n; i++ {
		fmt.Printf(format,
			t.Method(i).Name,
			t.Method(i).Func.Type(),
			v.Method(i).Type(),
		)
	}
	fmt.Println()
}



PHP: <?
class Foo {
    function bar(int $x) {
    }
}

$method_names = get_class_methods('Foo');
foreach ($method_names as $name) {
    echo "$name\n";
    $method_info = new ReflectionMethod('Foo', $name);
    echo $method_info;
}
?>
Task: Send an unknown method call




Go: package main

import (
    "fmt"
    "reflect"
)

type example struct{}


func (example) Foo() int {
    return 42
}

func main() {
    
    var e example
    
    m := reflect.ValueOf(e).MethodByName("Foo")
    
    r := m.Call(nil)
    
    fmt.Println(r[0].Int()) 
}



PHP: <?php
class Example {
  function foo($x) {
    return 42 + $x;
  }
}

$example = new Example();

$name = 'foo';
echo $example->$name(5), "\n";        // prints "47"

echo call_user_func(array($example, $name), 5), "\n";
?>
Task: Variables




Go: x := 3



PHP: <?php





# NULL typed variable
$null = NULL;				var_dump($null);	// output: null

# defining a boolean
$boolean = true;			var_dump($boolean);	// output: boolean true
$boolean = false;			var_dump($boolean);	// output: boolean false


# bool and boolean is the same
$boolean = (bool)1;			var_dump($boolean);	// output: boolean true
$boolean = (boolean)1;			var_dump($boolean);	// output: boolean true

$boolean = (bool)0;			var_dump($boolean);	// output: boolean false
$boolean = (boolean)0;			var_dump($boolean);	// output: boolean false

# defining an integer
$int = 0;				var_dump($int);		// output: int 0

# defining a float,
$float = 0.01;				var_dump($float);	// output: float 0.01

# which is also identical to "real" and "double"
var_dump((double)$float);					// output: float 0.01
var_dump((real)$float);						// output: float 0.01

# casting back to int (auto flooring the value)
var_dump((int)$float);						// output: int 0
var_dump((int)($float+1));					// output: int 1
var_dump((int)($float+1.9));					// output: int 1

# defining a string
$string = 'string';
var_dump($string);						// output: string 'string' (length=6)

# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);


$string = "I'm the same string!";
var_dump($another_string);

# "deleting" a variable from memory
unset($another_string);

$string = 'string';

$parsed_string = "This is a $string";
var_dump($parsed_string);

$parsed_string .= " with another {$string}";
var_dump($parsed_string);


# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);


# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);


# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass();	var_dump($stdObject);

# defining an object typed Foo
class Foo {}
$foo = new Foo();		var_dump($foo);

# defining an empty array
$array = array();		var_dump($array);



$assoc = array(
	0 => $int,
	'integer' => $int,
	1 => $float,
	'float' => $float,
	2 => $string,
	'string' => $string,
	3 => NULL, // <=== key 3 is NULL
	3, // <=== this is a value, not a key (key is 4)
	5 => $stdObject,
	'Foo' => $foo,
);
var_dump($assoc);




















function a_function()
{
	# not reachable
	var_dump(isset($foo));				// output: boolean false

	global $foo;
	# "global" (reachable) inside a_function()'s scope
	var_dump(isset($foo));				// output: boolean true
}

a_function();
Task: Runtime evaluation_In an environment




Go: package main

import (
    "bitbucket.org/binet/go-eval/pkg/eval"
    "fmt"
    "go/parser"
    "go/token"
)

func main() {
    
    squareExpr := "x*x"

    
    fset := token.NewFileSet()
    squareAst, err := parser.ParseExpr(squareExpr)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    w := eval.NewWorld()

    
    wVar := new(intV)

    
    err = w.DefineVar("x", eval.IntType, wVar)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    squareCode, err := w.CompileExpr(fset, squareAst)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    *wVar = 5
    
    r0, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    
    *wVar--
    
    r1, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}


type intV int64

func (v *intV) String() string              { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64      { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
    *v = intV(o.(eval.IntValue).Get(t))
}



PHP: <?php
function eval_with_x($code, $a, $b) {
    $x = $a;
    $first = eval($code);
    $x = $b;
    $second = eval($code);
    return $second - $first;
}
 
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
Task: Runtime evaluation




Go: package main
import (
	"fmt"
	"bitbucket.org/binet/go-eval/pkg/eval"
	"go/token"
)

func main() {
	w := eval.NewWorld();
	fset := token.NewFileSet();

	code, err := w.Compile(fset, "1 + 2")
	if err != nil {
		fmt.Println("Compile error");
		return
	}

	val, err := code.Run();
	if err != nil {
		fmt.Println("Run time error");
		return;
	}
	fmt.Println("Return value:", val) 

}



PHP: <?php
  $code = 'echo "hello world"';
  eval($code);
  $code = 'return "hello world"';
  print eval($code);
Task: Permutations with repetitions




Go: package main

import "fmt"

var (
    n      = 3
    values = []string{"A", "B", "C", "D"}
    k      = len(values)
    decide = func(p []string) bool {
        return p[0] == "B" && p[1] == "C"
    }
)

func main() {
    pn := make([]int, n)
    p := make([]string, n)
    for {
        
        for i, x := range pn {
            p[i] = values[x]
        }
        
        fmt.Println(p)
        
        if decide(p) {
            return 
        }
        
        for i := 0; ; {
            pn[i]++
            if pn[i] < k {
                break
            }
            pn[i] = 0
            i++
            if i == n {
                return 
            }
        }
    }
}



PHP: <?php
function permutate($values, $size, $offset) {
    $count = count($values);
    $array = array();
    for ($i = 0; $i < $size; $i++) {
        $selector = ($offset / pow($count,$i)) % $count;
        $array[$i] = $values[$selector];
    }
    return $array;
}

function permutations($values, $size) {
    $a = array();
    $c = pow(count($values), $size);
    for ($i = 0; $i<$c; $i++) {
        $a[$i] = permutate($values, $size, $i);        
    }
    return $a;
}

$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
    echo join(',', $permutation)."\n";
}