创建唯一的随机数 [英] Creating unique random numbers

查看:117
本文介绍了创建唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下方法以创建唯一的随机数。 (此唯一值属于树的节点):

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 


推荐答案

问题在于如果找到重复的数字,你不会在check函数内停止for循环。循环继续,b可以变回true。

The problem is that you don't stop the for loop inside the check function if it finds a duplicated number. The loop continues and b can change back to true.

你应该做的是例如:

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

这篇关于创建唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆