Re: Math.random()




maya wrote:
maya wrote:
hi,

what I actually want is to generate a LIST of nos, between 1 and a
variable.. I found this way:


however, I would like to tell it to NOT REPEAT a no. in the list, i.e.,
what I want is a list betw. 1 and a given no., but that no number appears
more than once in the list.. is this possible??


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class Test {

public static void main(String[] args) {
List<Integer> randomIntegers =
new ArrayList<Integer>
(NoDuplicateListOfRandomIntegers.
getRandomList(100, 1, 999));
for(int i = 0; i < randomIntegers.size(); i++) {
System.out.println(i + " " + randomIntegers.get(i));
}
}

public static class NoDuplicateListOfRandomIntegers {

private static Random rand = new Random();

public static List<Integer> getRandomList(int size, int low, int high) {
if(high <= size) {
throw new IllegalArgumentException();
}
Set<Integer> integers = new HashSet<Integer>();
while(integers.size() < size) {
integers.add(rand.nextInt(high - low + 1 ) + low);
}
List<Integer> ret = new ArrayList<Integer>();
ret.addAll(integers);
return ret;
}
}
}


.