首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法获取每次创建对象时生成的随机数

无法获取每次创建对象时生成的随机数
EN

Stack Overflow用户
提问于 2016-07-29 02:38:48
回答 2查看 65关注 0票数 0

我一遍又一遍地用相同的参数创建一个对象。这个对象有一个随机方法(使用Math.random()),我知道它每次都应该返回一个不同的数字,但每次在程序中创建一个新的类对象并调用该对象上的方法时,它都返回相同的值。我该如何解决这个问题呢?

我调用方法契约的地方:

代码语言:javascript
复制
for (int i = 0; i < 212000; i++){
            Contractions c = new Contractions(a, b);
            temp = c.contract();
            if (temp < min){
                min = temp;
            }
            if (i%1000 == 0){
                System.out.println(min);
            }
        }

方法:

代码语言:javascript
复制
while (vertices.size() > 2){
        Edge randEdge = edges.get((int) (Math.random()*edges.size()));
        vertices.remove(randEdge.getTwo());
        for (int i = edges.size() - 1; i >= 0; i--){
            if (edges.get(i).getOne() == randEdge.getTwo()){
                edges.get(i).setOne(randEdge.getOne());
            }
            if (edges.get(i).getTwo() == randEdge.getTwo()){
                edges.get(i).setTwo(randEdge.getOne());
            }
        }
        edges.remove(randEdge);
        removeSelfLoops();

return edges.size();

edge类:

代码语言:javascript
复制
package Contractions;

public class Edge {
    Vertex one;
    Vertex two;
    public Edge(Vertex one, Vertex two){
        this.one = one;
        this.two = two;
    }
    public boolean isEqual(Edge other){
        if (other.one == this.one && other.two == this.two){
            return true;
        }
        if (other.two == this.one && other.one == this.two){
            return true;
        }
        return false;
    }
    public Vertex getOne(){
        return one;
    }
    public Vertex getTwo(){
        return two;
    }
    public void setOne (Vertex v){
        one = v;
    }
    public void setTwo (Vertex v){
        two = v;
    }
    public String toString(){
        return one + "; " + two;
    }
}
EN

回答 2

Stack Overflow用户

发布于 2016-07-29 03:06:33

尝试使用带有nextInt(int bound)方法的Java Random。假设边界是包含边的列表的长度。这将返回一个介于0和bound之间的随机整数。

您现在使用的方法返回一个介于0和1之间的数字。然后将结果转换为int。由于您所使用的生成器的原因,您可能无法获得您期望的那种分布。

票数 1
EN

Stack Overflow用户

发布于 2016-07-29 02:45:52

据我所知,您返回的是edges.size()而不是randEdge。假设你没有改变边数组,你将总是返回相同的东西。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38644325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档