fisher-yates


See On Github

Data

Contributor

Generic placeholder thumbnail

by mitogh

in php

Tags

shuffle

Source Code

<?php
function fisher_yates($a = []){
    $n = count($a);
    for($i = 0; $i < $n; $i++){
        $j = mt_rand(0,$i);
        $tmp = $a[$j];
        $a[$j] = $a[$i];
        $a[$i] = $tmp;
    }
    return $a;
}
<?php
require 'fisher_yates.php';
class FisherYates_Test extends PHPUnit_Framework_TestCase{
    private $test = [1,2,3,4,5,6,7,8,9];

    public function testEmptyArray(){
        $this->assertEquals([], fisher_yates([]));
    }

    public function testShuffleArray(){
        $tmp = $this->test;
        $this->assertNotEquals($this->test, fisher_yates($tmp));
    }
}