note 99886 added to function.shuffle
| From: | A dot Lepedev+php at alepe dot com | Date: | Mon, 13 Sep 2010 04:24:56 +0000 |
| Subject: | note 99886 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172505@lists.php.net to get a copy of this message | ||
<?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.
?>
----
Server IP: 69.147.83.197
Probable Submitter: 211.6.179.194
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- https://master.php.net/note/edit/99886
Del: integrated -- https://master.php.net/note/delete/99886/integrated
Del: useless -- https://master.php.net/note/delete/99886/useless
Del: bad code -- https://master.php.net/note/delete/99886/bad+code
Del: spam -- https://master.php.net/note/delete/99886/spam
Del: non-english -- https://master.php.net/note/delete/99886/non-english
Del: in docs -- https://master.php.net/note/delete/99886/in+docs
Del: other reasons-- https://master.php.net/note/delete/99886
Reject -- https://master.php.net/note/reject/99886
Search -- https://master.php.net/manage/user-notes.php