0

Ok so i have looked about for an answer. I am using a random generator to generate numbers based on the user input. This will then select a random number from that and assign them a special position in the game. However the problem is i keep getting repeated values which isn't what i want. So could anyone help?

in

(blueprint class)

int getRoll()
{

    roll=rand.nextInt(totalNum);
    return roll;

}

(main class)

for(numberOfWerewolves=0;numberOfWerewolves!=wolves.werewolfNum;numberOfWerewolves++)
{
    playerNumber++;
    wolves.getRoll();
    System.out.println(wolves.roll);

}

anyone can help me would be great thanks

therealrootuser
  • 10,215
  • 7
  • 31
  • 46
daniel
  • 65
  • 1
  • 1
  • 7

2 Answers2

0

It sounds like you want several random numbers within the same range, but you don't want any repeats. If so, what you want is called a "shuffle." Fill an array with the numbers from 1 to N (or 0 to N-1, or whatever), shuffle the array, and then start using the numbers from the beginning of the array.

A good description and implementation of shuffling is given here:

https://stackoverflow.com/a/1520212/1441122

Community
  • 1
  • 1
Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
0

Create a list to keep track of previous random numbers, and loop to keep recalculating the random number until it doesn't match any of them in the list:

public static boolean checkIfExists(ArrayList<Double> list, double x) {

    for (double d : list) {
        if (d == x) {
            return false;
        }
    }
    return true;
}

ArrayList<Double> list = new ArrayList<Double>();

int getRoll()
{  
    while (true) {
        roll = rand.nextInt(totalNum);
        if (checkIfExists(list, roll)) {
            list.add(roll);
            return roll;
        }
    }        
    return -100; // -100 means it couldn't generate a number
}

You should not keep the while condition to be true; you should modify it so that it only loops for until you're sure that a unique number can't be generated.

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97