note 99886 deleted from function.shuffle by danbrown
| From: | danbrown@php.net | Date: | Mon, 13 Sep 2010 17:47:32 +0000 |
| Subject: | note 99886 deleted from function.shuffle by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172517@lists.php.net to get a copy of this message | ||
Note Submitter: A dot Lepe dev+php at alepe dot com
----
<?php
/*
* It does the same job as shuffle($array) but
* coded to be able to un-shuffle arrays.
* based in: [ rick at suggestive dot com ]
* modified by: Alberto Lepe
*/
function arr_shuffle($arr) {
$l = count($arr) -1;
for ($i = $l; $i >= 0; $i--){
$j = rand(0, $l);
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
}
return $arr;
}
/*
* @author: Alberto Lepe
*/
function arr_unshuffle($arr) {
$r = array();
$l = count($arr) -1;
for($i=0; $i <= $l; $i++) $r[] = rand(0, $l);
$r = array_reverse($r);
for ($i=0; $i <= $l; $i++) {
$j = $r[$i];
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
}
return $arr;
}
/* EXAMPLE */
//----- To shuffle: -------
srand(123456); //Use any number as key.
$a = str_split("hello world");
$b = arr_shuffle($a);
echo implode("",$b); //return "olhrle dlow"
//----- To un shuffle: ------
srand(123456); //Use the same number as above.
$c = arr_unshuffle($b);
echo implode("",$c); //return "hello world"
//NOTE: you can use mt_rand and mt_srand instead if you want.
?>