-2
//Generates a random number but doesn't allow the same number be repeated
for (int i = 0; i < questions1.length; i++)
{
  //random number
  int r = (int)(Math.random() * i);
  temp = index[r];
  index[r] = index[i];
  index[i] = temp;
}

How do I make it favour 1 number in particular?

Rick Ross
  • 43
  • 1
  • 6

3 Answers3

4

If you want, for example, a random number between 1-6, but want 3 to be picked twice as likely as any other number, a very simple solution would be to create an array with 7 indexes. 1, 2, 4, 5, 6 all hold one index each. 3 holds two indices. Now pick a random number between 0 and 6 and return whatever number is in that index.

Using this approach you can provide whatever weights you want to any range of numbers.

There are almost certainly more elegant solutions, but this will get the job done.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
2

You could build an List and fill it with the numbers you want in the proportion you want. Then use Collections.shuffle.

public void test() {
    // Throw 1 twice as likely and 6 3 times as likely as the other numbers.
    List dice = Arrays.asList(1,1,2,3,4,5,6,6,6);
    Collections.shuffle(dice);
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • 1
    Quite elegant... Problem may arise if the proportions are not "simple", like: "1 should appear with a probability of 42.345%" - but that is not necessarily what is being asked. – assylias Jan 12 '14 at 16:01
0

Let's say your target range is [0, 6] and you give 1 twice the likelihood. I'll give you two methods which won't eat your memory:

  1. Select a random number out of [0, 7] and map 7 to 1
  2. Select a random out of [0, 6] and if it's not 1 return a new random number out of [0, 6].
Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67