2

How do you generate random numbers that go up by twos using Math.random()? For example, I'm trying to generate a random number from the set (2,4,6,8), how would you go it?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user2000624
  • 29
  • 1
  • 3
  • 2
    So, you don't mean 'generate' a random number? You just want to pick a random index from an array of numbers? – Rohan Oct 02 '13 at 00:03

7 Answers7

6

For this specific set you could use

(int)(Math.random() * 4) * 2 + 2

Here:

  • Math.random() generates a number that's greater or equal to 0.0 and strictly less than 1.0;
  • (int)(... * 4) gives one of 0, 1, 2, 3.
  • ... * 2 + 2 gives one of 2, 4, 6, 8.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

Okay, let's make a real general solution.

int lower = 2;
int upper = 8;
int step = 2;
int rand = (int)(Math.random() * (upper-lower+1));
int result = rand - rand%step + lower;

If you want to generate numbers within another set than the one you specified, just change the lower, upper and step variables to fit your set. It includes the upper bound if it's in the set.

spydon
  • 9,372
  • 6
  • 33
  • 63
  • 1
    You need parens around (upper-lower+2) in that expression. Also, you can do the (rand - rand%2) without a division, using (rand&-2). If you want to leave the division in, you can get a more general solution where any arithmetic progression can be described with (upper), (lower) along with a (step) value specifying the common difference. – Mike Housky Oct 02 '13 at 01:38
  • Thank you, fixed it accordingly. – spydon Oct 02 '13 at 02:44
  • Good enough for an upvote. :) I also note that you correctly changed (upper-lower+2) to (upper-lower+1) to allow for a step of 1. Well done! – Mike Housky Oct 02 '13 at 05:05
1

The (almost) completely general approach isn't that hard.

static randInt(int first, int last, int step) {
    int nsteps = (last+1-first) / step;
    return first + step*(int)(nsteps*Math.random());
}

That returns a random integer from {start, start+step, start+2*step, ... } up to and including stop, or the last number before stop if stop is not part of the sequence.

int choice = randInt(2, 8, 2); /* random choice from {2, 4, 6, 8} */

...solved the sample question.

The (almost) part is that this doesn't handle integer overflow or sign errors in the arguments (step is zero, step<0 when first<last, or vice versa.)

Mike Housky
  • 3,959
  • 1
  • 17
  • 31
0
int[] numSet={2,4,6,8};
Random myRand=new Random();
int myNum=numSet[myRand.nextInt(numSet.length)];

This creates an array of numbers, the random object, then picks a random element from the array of numbers. This does not assume that the numbers are in any sort of mathematical series. They could be 11, 25, 31, 876, 984368, 7432, 84562, for that matter.

Please don't tell me that there's a polynomial that generates that set from its y-values. I know.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • What if the set goes up to one million? You'd have to store all of the numbers in an array unnecessarily. – arshajii Oct 02 '13 at 00:07
  • @arshajii Given the vagueness of the current original question, all answers would be partially correct and partially unworkable as we do not know the OP's parameters. AFAICT there was a 5-minute-window edit but I can't be too sure. – nanofarad Oct 02 '13 at 00:09
  • There's a small danger here that someone will copy this code verbatim, and creating a new Random() object for each new choice is much less "random" than consecutive values from the same Random object. Still, it superior if the coder is careful to create that object just once and reuse it for multiple calls or iterations, if only because it's more likely to be thread-safe. – Mike Housky Oct 02 '13 at 05:14
0

Put those numbers in an array. Generate a random number using the length of the array - 1 and use it as the index to randomly choose an array element.

edhedges
  • 2,722
  • 2
  • 28
  • 61
0

You can also use the java.util.Random class like this:

    int values[] = {2,4,6,8};
    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(values.length);
    int randomValue = values[randomInt]; /* Here's your random value from your set */ 
Fabio
  • 791
  • 1
  • 7
  • 27
0

I would like to add a more general answer.

Assume the smallest integer in the set is A and the size of the set is S. A random integer from the set would be like this:

A + myRandom.nextInt(S) * 2

For your specific example in Java, it would be:

Random myRandom = new Random();
int randomNum = 2 + myRandom.nextInt(4) * 2;
Terry Li
  • 16,870
  • 30
  • 89
  • 134