我被要求编写一个程序(主要是一种方法)来改组一副牌.我写了以下程序:
public class Deck {
////////////////////////////////////////
// Data Members
////////////////////////////////////////
private Card[] cards; // array holding all 52 cards
private int cardsInDeck; // the current number of cards in the deck
public static final int DECK_SIZE = 52;
/**
* Shuffles the deck (i.e. randomly reorders the cards in the deck).
*/
public void shuffle() {
int newI;
Card temp;
Random randIndex = new Random();
for (int i = 0; i < cardsInDeck; i++) {
// pick a random index …Run Code Online (Sandbox Code Playgroud) 我知道类似的问题出现了很多,而且可能没有确定的答案,但我想从一个可能无限的数字子集中生成五个唯一的随机数(可能是0-20,或0-1,000,000).
唯一的问题是我不想运行while循环或填充数组.
我目前的方法是简单地从子集中减去最后五个数字生成五个随机数.如果任何数字彼此匹配,则它们将在子集的末尾到达它们各自的位置.因此,如果第四个数字与任何其他数字匹配,则它将从最后一个数字下注设置为第4个.
有没有人有一个"足够随机"的方法,并且不涉及昂贵的循环或数组?
请记住这是一个好奇心,而不是一些关键任务问题.如果每个人都没有发帖"你为什么会遇到这个问题?"我将不胜感激.答案.我只是在寻找想法.
非常感谢!
我意识到使用random不会生成真正的随机数,但我不明白为什么这段代码不能用来防止重复.目标是从0到44之间(并且不包括)导出8个唯一数字.运行代码时没有任何错误,但重复确实发生:
//Loop Begins Within Main
for (int i = 0; i < 8; i++)
{
//Begins Recursion
int x = Unique8(rndm, num8);
num8[i] = x;
}
//Recursion Takes Place Outside of the Main with Static Declarations
static Random rndm = new Random();
static int[] num8 = new int[8];
static int Unique8 (Random rndm, int[] num8)
{
int x = rndm.Next(1, 43);
//Seeks if Number is Repeated
if (num8.Contains(x))
{
//If So, Recursion Takes Place
Unique8(rndm, num8);
}
//Returns Value to …Run Code Online (Sandbox Code Playgroud)