A Data Randomization Algorithm

When developing a card game or a match game, you need to reshuffle or reposition things, which means shuffling the data. So let’s take the most common example — a deck of playing cards — and build a data randomization algorithm.

Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 function new_rand($arr){
$len=count($arr);
$new_arr=[];
for($i=0;$i<$len;$i++){
$new_arr[mt_rand()]=$arr[$i];
}
ksort($new_arr);
return array_values($new_arr);
}

$arr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,
33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,
49,50,51,52,53,54];
echo "原始结果".PHP_EOL;
print_r(json_encode($arr));
$get_arr=new_rand($arr);
echo PHP_EOL."最终结果".PHP_EOL;
print_r(json_encode($get_arr));

The final result is shown in the image:
erik.xyz