题目描述:
要求开发一款扑克游戏,编写一套洗牌算法,而公平地洗牌是将洗好的牌存储在一个整型数组里。
实现代码如下:
<?php
$cardNum = 54;
print_r(washCard(54));
function washCard($cardNum){
$result = $tmp = [];
//生成0~53的array
$tmp = range(0,$cardNum-1);
for($i = 0; $i < $cardNum; $i++){
//随机找一个值
$index = rand(0, $cardNum - $i - 1);
//值赋给$result
$result[$i] = $tmp[$index];
//去掉
unset($tmp[$index]);
//格式化数组,key从0开始递增1
$tmp = array_values($tmp);
}
return $result;
}
洗牌的结果是随机不唯一的,我的是。
Array
(
[0] => 39
[1] => 27
[2] => 18
[3] => 44
[4] => 47
[5] => 4
[6] => 52
[7] => 50
[8] => 16
[9] => 15
[10] => 12
[11] => 7
[12] => 13
[13] => 41
[14] => 46
[15] => 5
[16] => 49
[17] => 26
[18] => 10
[19] => 19
[20] => 43
[21] => 8
[22] => 9
[23] => 40
[24] => 48
[25] => 17
[26] => 34
[27] => 45
[28] => 53
[29] => 37
[30] => 2
[31] => 25
[32] => 11
[33] => 0
[34] => 30
[35] => 32
[36] => 33
[37] => 51
[38] => 14
[39] => 36
[40] => 22
[41] => 28
[42] => 31
[43] => 35
[44] => 1
[45] => 6
[46] => 24
[47] => 3
[48] => 21
[49] => 23
[50] => 42
[51] => 38
[52] => 29
[53] => 20
)