enn*_*nth 1 java random algorithm shuffle
我试图在常见的 Java 洗牌算法中更好地理解这段代码:
// Random for remaining positions.
int r = i + rand.nextInt(52 - i);
Run Code Online (Sandbox Code Playgroud)
为什么需要“填充”或i向结果随机数添加索引?看起来,当您迭代和添加 时i,通过减去i,您可以将最大可能的随机数范围保持在 0 到 51 之间,但为什么不这样做:
int r = rand.nextInt(52);
Run Code Online (Sandbox Code Playgroud)
完整代码:
// Function which shuffle and print the array
public static void shuffle(int card[], int n)
{
Random rand = new Random();
for (int i = 0; i < n; i++)
{
// Random for remaining positions.
int r = i + rand.nextInt(52 - i);
//swapping the elements
int temp = card[r];
card[r] = card[i];
card[i] = temp;
}
}
Run Code Online (Sandbox Code Playgroud)