java - How to generate unique random numbers? -
i trying solve problem.i have define array 5 elements on , define random generator method 3 defined integersi1,i2,i3 different each other.so when variables generated have different .i hope clear.can please me ,or suggestion welcome.
import java.util.*; public class array { public static void main(string[] arg) { int[] v = { 1, 2, 3, 4, 5 }; displayarray(v); array n = new array(); n.randomgenerator(); } private static void displayarray(int[] arr) { (int x : arr) system.out.print(x + " "); system.out.println(); } public int[] randomgenerator() { int[] = new int[3]; int i1; int i2; int i3; (int = 0; < a.length; i++) { a[i] = (int) (math.random() * 5); } i1 = a[0]; i2 = a[1]; i3 = a[2]; if (i1 != i2 && i2 != i3 && i1 != i3) { system.out.println(i1 + "," + i2 + "," + i3); } else { if (i1 == i2 && i2 == i3 && i1 == i3) { } } return a; } }
there 2 options using this:
one possibility while generating new random number check if it's of existing random numbers , if so, retry generation. in theory, take long amount of time in practice it's fast.
another option e.g. if want generate random numbers in range 0-9 (inclusive-inclusive) , if have e.g. 3 , 7, generate math.random()%8 instead of math.random()%10 , if number greater or equal 3, increment one, , if new number greater or equal 7, increment one.
Comments
Post a Comment