|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
void shuffle(int array[], int length)
{
int index, temp, i;
srand(time(NULL));
for (i = 0; i < length; i++)
{
index = rand() % (length - i) + i;
if (index != i)
{
temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}
}
[backcolor=Red]我想问下 index中为啥随机数取值是(length-i)+i
本帖最后由 jackz007 于 2019-8-17 19:25 编辑
这个表达式根据 length 和 i 的值,确定了每次循环产生随机数的数值范围
- index = rand() % (length - i) + i;
复制代码
假设 length = 10,那么,将会循环 10 次。
- i = 0 : rand() % 10 = 0 ~ 9 , index : 0 ~ 9
- i = 1 : rand() % 9 = 0 ~ 8 , index : 1 ~ 9
- i = 2 : rand() % 8 = 0 ~ 7 , index : 2 ~ 9
- i = 3 : rand() % 7 = 0 ~ 6 , index : 3 ~ 9
- . . . . . .
- i = 8 : rand() % 2 = 0 ~ 1 , index : 8 ~ 9
- i = 9 : rand() % 1 = 0 , index : 9
复制代码
上面的代码十分巧妙,假设有 10 张牌(length = 10),那么,第一张牌(i = 0)有 10 种发法(0~9),第二张牌(i = 1)有 9 种(1~9)。。。,第十张牌(i = 9)只剩下 1 种发法(9)。
|
|