Creating unique random numbers

2019-02-19 00:42发布

I have created the following method so as to create unique random numbers . (This unique values belong to the nodes of a 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 doesn’t create unique numbers and there are still duplicates in my list. Like :

0: 10
1: 1 
2: 10 
3: 5 
4: 6 

标签: java random
8条回答
成全新的幸福
2楼-- · 2019-02-19 01:20

You "forget" to use the numList that you've prepared.

This code should work fine:

static Random rand = new Random();

public static ArrayList<Node> go(int n) {
    ArrayList<Node> list = new ArrayList<Node>();
    ArrayList<Integer> numList = new ArrayList<Integer>();

    for (int i = 1; i <= 5; i++) {
        int number = rand.nextInt(10) + 1;
        if (numList.contains(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;

}
查看更多
欢心
3楼-- · 2019-02-19 01:20

You should change your check method to something like:

  private static boolean check(ArrayList<Node> list, int num)
  {
    for (Node node : list)
        if (node.data == num)
            return false;

    return true;
  }

In this way you go over the list and return false as soon as you find an equal element. If you are able to finish the loop without returning then no duplicates are found and you can return true.

查看更多
登录 后发表回答