我一遍又一遍地用相同的参数创建一个对象。这个对象有一个随机方法(使用Math.random()),我知道它每次都应该返回一个不同的数字,但每次在程序中创建一个新的类对象并调用该对象上的方法时,它都返回相同的值。我该如何解决这个问题呢?
我调用方法契约的地方:
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);
}
}方法:
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类:
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;
}
}发布于 2016-07-29 03:06:33
尝试使用带有nextInt(int bound)方法的Java Random。假设边界是包含边的列表的长度。这将返回一个介于0和bound之间的随机整数。
您现在使用的方法返回一个介于0和1之间的数字。然后将结果转换为int。由于您所使用的生成器的原因,您可能无法获得您期望的那种分布。
发布于 2016-07-29 02:45:52
据我所知,您返回的是edges.size()而不是randEdge。假设你没有改变边数组,你将总是返回相同的东西。
https://stackoverflow.com/questions/38644325
复制相似问题