I want an interval of numbers between 0 and 9 using random generator. For example, if I already received 0,2,7 i don't want those numbers again, instead i want one of the rest between the given interval[1 or 3 or 4 or 5 or 6 or 8 or 9].
Asked
Active
Viewed 144 times
4 Answers
3
As Boris the Spider says:
// We want numbers between 0 and 9 inclusive
int min = 0, max = 9;
// We need a Collection, lets use a List, could use any ordered collection here
List<Integer> nums = new ArrayList<>();
// Put the numbers in the collection
for (int n=min; n<=max; n++) { nums.add(n); }
// Randomly sort (shuffle) the collection
Collections.shuffle(nums);
// Pull numbers from the collection (the order should be random now)
for (int count=0; count<nums.length; count++) {
System.out.println("Number " + count + " is " + nums.get(count));
}

Mike Tunnicliffe
- 10,674
- 3
- 31
- 46
0
This solution runs in better time performance with math.random.
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(1);
numbers.add(2); //or more
while (!numbers.isEmpty()) {
System.out.println(numbers.remove((int) (Math.random() * numbers.size())));
}

Ruben Verboon
- 73
- 6
-1
This is an alternative approach to Java.util.Collections
, which uses the Java.util.Random
class.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
final static int RAND_CAP = 9;
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<Integer> usedNumbers = new ArrayList<Integer>();
Random rand = new Random(System.currentTimeMillis());
while (usedNumbers.size() < RAND_CAP) {
int randNum = Math.abs(rand.nextInt() % RAND_CAP) + 1;
if (!usedNumbers.contains(randNum)) {
usedNumbers.add(randNum);
System.out.println(randNum);
}
}
}
}

David.Jones
- 1,413
- 8
- 16
-
This is very poor as performance degrades as you reach the end of the required numbers. In fact, there is no reason the second number should ever return - `random.nextInt` can keep returning the same number. Further `List.contains` is `O(n)`, `Set.contains` is `O(1)`. This answer shows a fundamental misunderstanding of both programmatic randomness and the Java collections API. – Boris the Spider Dec 02 '14 at 08:17