2

I am trying to set up a game of Deal or No Deal. I need to assign one of the money values to each case. I was wondering if this would be possible and if so, how. I would set up 2 arrays, case for the case number (1-26) and money for the different values (specific numbers between 1 and 1,000,000 that I would set at the beginning). I then would like to take a random value out of array money and assign it a value in array case but also check to make sure it isn't already stored in another case variable.

int cases[]=new int[26];
int money = {1,2,,5,10,25,50,75,100,200,300,400,...};

Every value stored in money will be used once and only once. Every case will get assigned one and only one value.

Phoenix
  • 23
  • 4
  • 4
    Possible duplicate: http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array – Novak Nov 08 '15 at 16:13

2 Answers2

4

Use an ArrayList instead.

ArrayList<Integer> money = ....;

for (int i = 0; i < 26; i++){
    int pick = (int)(Math.random() * money.size());
    cases[i] = money.remove(pick);
}

However, if you're going to use an ArrayList, you may as well take advantage of the wealth of methods found in Collections, such as Collections#shuffle. Per the docs,

Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

You could then use the method like so:

ArrayList<Integer> money = ....;
Collections.shuffle(money);
//money is now functionally what `cases` used to be
Michael
  • 2,673
  • 1
  • 16
  • 27
  • Ok, would I replace the ... with the money values separated by commas? – Phoenix Nov 08 '15 at 16:22
  • @Phoenix No, look at this post for the best initialization practices http://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line – Michael Nov 08 '15 at 16:23
0

You should have at least 26 values in money[] array

    int cases[]=new int[26];
    int[] money = {1,2,5,10,25,50,75,100,200,300,400....};
    Random random = new Random();
    int index = 0;
    firstLoop:
    while(cases[25]==0){
        int randomChosenIndex = random.nextInt(money.length);
        int randomChosenValueFromMoney = money[randomChosenIndex];
        for (int i = 0; i < index; i++) {
            if (cases[i]==randomChosenValueFromMoney) {
                continue firstLoop;
            }
        }
        cases[index++] = randomChosenValueFromMoney;
    }
Andrei Amarfii
  • 685
  • 1
  • 6
  • 17