How do i restrict a Java random number generation -
here deal: have java code generates random number between 2 numbers , works fine. i'm trying achieve something. want in such way after first number has been generated, when recalls it, doesn't generate same number. instance, if number 4 generated, want included among possible generated numbers second time. make things little bit clear, here's code.
int maximum=10; int minimum=1; int r; r = (int)(math.random() * maximum) + minimum;
is there can make code above not generate particular number between 1 , 10? thanks.
you fill collection , removed randomly selected number:
list<integer> nums = new arraylist<>(); (int = /* start */; < /* end */; i++) { nums.add(i); } //elsewhere random rand = new random(); int = nums.remove(rand.nextint(/* end */); /* end */--;
this may bit slower large amounts of numbers end result lower time-complexity on checks new numbers (whereas while loop in theory o(∞n)
if i'm not mistaken)
alternatively, use collections#shuffle
Comments
Post a Comment