2

How can I make sure that a random number is only generated once?

For example:

for(int i = 0; i<len; i++)
    {
        while (rands.contains(rand = r.nextInt(len-2)+1));
        rands.add(rand);
        System.out.print ("Rand ___ " + rand + "___");
    }

How can I make sure that if the number 2 is generated from rand, it wont be generated again?

I apologise if i am not making myself clear enough. Please comment if you require any more information.

Thanks.

Stephen P
  • 14,422
  • 2
  • 43
  • 67
faraday
  • 51
  • 1
  • 1
  • 5
  • 3
    What are you actually trying to do? If you need the numbers 0-2 generated in a random order you might want to just use Collections.shuffle(List). – Mike Deck Jul 30 '12 at 19:39
  • 1
    You can probably find your answer [here](http://stackoverflow.com/questions/196017/unique-random-numbers-in-o1), as the same question is asked. – Viktor Jul 30 '12 at 19:39
  • Of course, once you start excluding previously used numbers it's no longer *random* – Stephen P Jul 30 '12 at 21:24

5 Answers5

1

You can't really constrain that when using Random API. May be you need to keep a list of already generated numbers and return the number if it is not already generated.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • is there any other way to do it? without Random API? – faraday Jul 30 '12 at 19:38
  • could i create a while loop that carries on running until its not equal to the numbers previously generated? – faraday Jul 30 '12 at 19:39
  • Another way may be, have a list (or) array of numbers and get number from that list (or) array. Keep another array for already visited index. If list, may be remove already visited number. – kosa Jul 30 '12 at 19:39
  • 1
    *Don't* use a list or array to store the past numbers; that would be the slowest way to do it. Use a `HashSet` or something similar. – Ernest Friedman-Hill Jul 30 '12 at 19:41
  • HashSet is collection/datastructure implementation. Read this link for more info. http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html – kosa Jul 30 '12 at 19:45
  • ok then i think this might work. Ill try right now and keep you all posted! – faraday Jul 30 '12 at 19:48
  • pleas help i dont know why its doing this – faraday Jul 30 '12 at 19:59
1

You'd have to store all the numbers you've generated, and check the new ones. Use a HashSet for performance' sake:

HashSet<Integer> rands = new HashSet<Integer>();
for(int i = 0; i<3; i++)
{
   int rand;
   while (rands.contains(rand = r.nextInt(3)))
       ;
   rands.add(rand);
}
Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
0

I'm assuming that you want to create a list of numbers from 0-2 in random order (If I'm wrong, let me know)

What you really want is to create a list of those numbers

ArrayList<Integer> randomNums = ArrayList<Integer>() {{ add(0); add(1); add(2); }}

Then use Collections to shuffle that.

Collections.shuffle(randomNums)
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
0

You need to use a shuffling algorithm for this. Start with 1. Create an array of Integers from 1 to 1000 (arbitrary Size). Shuffle the array well. keep fetching from the shuffled array till you run out of them. When you are through the 1000, repopulate the array with 1000-2000, shuffle, and use. Repeat the process as many times as you need.

srini.venigalla
  • 5,137
  • 1
  • 18
  • 29
0

If you just need a stream of non-repeating random numbers in some range you could do something like this:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class RandomNumberStream {
    private Iterator<Integer> numbers;

    public RandomNumberStream(int range) {
        List<Integer> numbersList = new ArrayList<>(range);
        for(int i = 0; i < range; i++) {
            numbersList.add(i);
        }
        Collections.shuffle(numbersList);
        numbers = numbersList.iterator();
    }

    public int nextNumber() {
        if(!numbers.hasNext()) {
            throw new IllegalStateException("No more numbers...");  //you might want to handle this differently
        }
        return numbers.next();
    }

    public static void main(String[] args) {
        RandomNumberStream rand = new RandomNumberStream(5);

        for(int i = 0; i < 5; i++) {
            System.out.println(rand.nextNumber());
        }
    }
}
Mike Deck
  • 18,045
  • 16
  • 68
  • 92