WeixiangYan/CodeTransOcean huggingface dataset:
Task: Substring_Top and tail




Go: 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])
}



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
?>
Task: Longest string challenge




Go: 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("")
}



PHP: <?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;
Task: Create a file




Go: 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")
}



PHP: <?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
mkdir('/docs');
?>
Task: Sorting algorithms_Strand sort




Go: 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
}



PHP: $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;
}
Task: Delegates




Go: 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()) 
}



PHP: 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" ;
Task: Enforced immutability




Go: package main

func main() {
    s := "immutable"
    s[0] = 'a'
}



PHP: define("PI", 3.14159265358);
define("MSG", "Hello World");
Task: Sutherland-Hodgman polygon clipping




Go: 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)
}



PHP: <?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";
?>
Task: Call a foreign-language function




Go: 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)
}



PHP: $ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll");

$cstr = $ffi->_strdup("success");
$str = FFI::string($cstr);
echo $str;
FFI::free($cstr);
Task: Knuth's algorithm S




Go: package main

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

func sOfNCreator(n int) func(byte) []byte {
    s := make([]byte, 0, n)
    m := n
    return func(item byte) []byte {
        if len(s) < n {
            s = append(s, item)
        } else {
            m++
            if rand.Intn(m) < n {
                s[rand.Intn(n)] = item
            }
        }
        return s
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    var freq [10]int
    for r := 0; r < 1e5; r++ {
        sOfN := sOfNCreator(3)
        for d := byte('0'); d < '9'; d++ {
            sOfN(d)
        }
        for _, d := range sOfN('9') {
            freq[d-'0']++
        }
    }
    fmt.Println(freq)
}



PHP: <?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);
?>
Task: Command-line arguments




Go: package main
import (
	"fmt"
	"os"
)

func main() {
	for i, x := range os.Args[1:] {
		fmt.Printf("the argument #%d is %s\n", i, x)
	}
}



PHP: <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
Task: Array concatenation




Go: 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)

}



PHP: $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
Task: User input_Text




Go: 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")
    }
}



PHP: #!/usr/bin/php
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN);
Task: First-class functions




Go: package main

import "math"
import "fmt"


func cube(x float64) float64 { return math.Pow(x, 3) }


type ffType func(float64) float64

func compose(f, g ffType) ffType {
    return func(x float64) float64 {
        return f(g(x))
    }
}

func main() {
    
    funclist := []ffType{math.Sin, math.Cos, cube}
    
    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
    for i := 0; i < 3; i++ {
        
        fmt.Println(compose(funclisti[i], funclist[i])(.5))
    }
}



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;
}
Task: Proper divisors




Go: package main

import (
    "fmt"
    "strconv"
)

func listProperDivisors(limit int) {
    if limit < 1 {
        return
    }
    width := len(strconv.Itoa(limit))
    for i := 1; i <= limit; i++ {
        fmt.Printf("%*d -> ", width, i)
        if i == 1 {
            fmt.Println("(None)")
            continue
        }
        for j := 1; j <= i/2; j++ {
            if i%j == 0 {
                fmt.Printf(" %d", j)
            }
        }
        fmt.Println()
    }
}

func countProperDivisors(n int) int {
    if n < 2 {
        return 0
    }
    count := 0
    for i := 1; i <= n/2; i++ {
        if n%i == 0 {
            count++
        }
    }
    return count
}

func main() {
    fmt.Println("The proper divisors of the following numbers are :\n")
    listProperDivisors(10)
    fmt.Println()
    maxCount := 0
    most := []int{1}
    for n := 2; n <= 20000; n++ {
        count := countProperDivisors(n)
        if count == maxCount {
            most = append(most, n)
        } else if count > maxCount {
            maxCount = count
            most = most[0:1]
            most[0] = n
        }
    }
    fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
    fmt.Println("namely", maxCount, "\b\n")
    for _, n := range most {
        fmt.Println(n)
    }
}



PHP: <?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";
Task: Regular expressions




Go: 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)
}



PHP: $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";
Task: Hash from two arrays




Go: 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)
}



PHP: $keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);
Task: Fractal tree




Go: package main







import (
    "math"
    "raster"
)

const (
    width  = 400
    height = 300
    depth  = 8
    angle  = 12
    length = 50
    frac   = .8
)

func main() {
    g := raster.NewGrmap(width, height)
    ftree(g, width/2, height*9/10, length, 0, depth)
    g.Bitmap().WritePpmFile("ftree.ppm")
}

func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
    x2 := x + distance*math.Sin(direction*math.Pi/180)
    y2 := y - distance*math.Cos(direction*math.Pi/180)
    g.AaLine(x, y, x2, y2)
    if depth > 0 {
        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
    }
}



PHP: <?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);
?>
Task: Gray code




Go: package main

import "fmt"

func enc(b int) int {
    return b ^ b>>1
}

func dec(g int) (b int) {
    for ; g != 0; g >>= 1 {
        b ^= g
    }
    return
}

func main() {
    fmt.Println("decimal  binary   gray    decoded")
    for b := 0; b < 32; b++ {
        g := enc(b)
        d := dec(g)
        fmt.Printf("  %2d     %05b   %05b   %05b  %2d\n", b, b, g, d, d)
    }
}



PHP: <?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));
}
Task: Arrays




Go: 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))

    
    
}



PHP: $NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange'];
Task: Sierpinski carpet




Go: package main

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

var order = 3
var grain = "#"

func main() {
    carpet := []string{grain}
    for ; order > 0; order-- {
        
        
        hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
        middle := make([]string, len(carpet))
        for i, s := range carpet {
            middle[i] = s + hole + s
            carpet[i] = strings.Repeat(s, 3)
        }
        carpet = append(append(carpet, middle...), carpet...)
    }
    for _, r := range carpet {
        fmt.Println(r)
    }
}



PHP: <?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;
}
Task: Sorting algorithms_Bogosort




Go: 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)
}



PHP: 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;
}
Task: Sequence of non-squares




Go: package main

import (
    "fmt"
    "math"
)

func remarkable(n int) int {
    return n + int(.5+math.Sqrt(float64(n)))
}

func main() {
    
    fmt.Println("  n  r(n)")
    fmt.Println("---  ---")
    for n := 1; n <= 22; n++ {
        fmt.Printf("%3d  %3d\n", n, remarkable(n))
    }

    
    const limit = 1e6
    fmt.Println("\nChecking for squares for n <", limit)
    next := 2
    nextSq := 4
    for n := 1; n < limit; n++ {
        r := remarkable(n)
        switch {
        case r == nextSq:
            panic(n)
        case r > nextSq:
            fmt.Println(nextSq, "didn't occur")
            next++
            nextSq = next * next
        }
    }
    fmt.Println("No squares occur for n <", limit)
}



PHP: <?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!");
	}
?>