Java – create a unique random number
•
Java
I created the following method to create a unique random number (this unique value belongs to the node of the tree):
static Random rand = new Random(); public static ArrayList<Node> go(int n) { ArrayList<Node> list = new ArrayList<Node>(); ArrayList<Integer> numList = new ArrayList<Integer>(); // TODO Auto-generated method stub for(int i = 1; i<=5; i++) { int number = rand.nextInt(10)+1; if(list.size()>0 && !check(list,number)) { i--; continue; } numList.add(number); Node node = new Node(); node.data = number; list.add(node); } int w = 0; for (Node d : list) { System.out.println(w+": "+d.data); w++; } return list; } private static boolean check(ArrayList<Node> list,int num) { // TODO Auto-generated method stub boolean b = false; /*if(list.size()==0) return true; */ for (Node node : list) { if(node.data == num) b = false; else b = true; } return b; }
But it won't create a unique number. There are still duplicate numbers in my list Like:
0: 10 1: 1 2: 10 3: 5 4: 6
Solution
The problem is that if duplicate numbers are found, you won't stop the for loop in the check function If the loop continues, B can change back to true
What you should do is, for example:
private static boolean check(ArrayList<Node> list,int num) { for (Node node : list) { if(node.data == num) return false; } return true; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码