So I am trying to generate an array that is filled with unique randomized integers and I found out that doing this with an arraylist would be the most efficient way to do so.
public static int [] randArr(int n, int max){
randArr = new int[n];
Random rn = new Random();
Set<Integer> test = new HashSet<Integer>();
while(test.size() < n){
test.add(rn.nextInt(0, max));
}
}
Now I tried working with randArr = test.toArray()
but I am not quite sure, what to put in the parentheses nor if this really can work. Is there any other method for converting, since I cannot simply assign randArr with the integers of test through test.get(i)
with a for-loop either.
CodePudding user response:
Don't use a set. Stream
the random numbers, remove dups using distinct
, and limit using limit
public static int [] randArr(int n, int max){
Random rn = new Random();
return rn.ints(0,max).distinct().limit(n).toArray();
}
Notes:
- Make certain that
n is <= max
, otherwise you could be waiting a while. max must be >= 1
(required byRandom.ints
method)
You may want to put in some code to enforce those invariants
and throw an appropriate exception if not in compliance. Something like the following (or whatever makes sense to you).
if (n > max || max <= 0) {
throw new IllegalArgumentException(
"n(%d) <= max(%d) or max > 0 not in compliance"
.formatted(n,max));
}