简体   繁体   中英

Unable to get random number to be generated every time object is created

I am creating an object with the same parameters multiple times over and over again. The object has a random method (using Math.random()) in it which I know should return a different number every time, but each time within the program I create a new object of that class and call the method on it, it returns the same value. How should I fix this?

place where I call the method contract:

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);
            }
        }

method:

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 class:

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;
    }
}

Try using Java Random with its nextInt(int bound) method. Let the bound be the length of the list that is holding the edges. This will return a random integer between 0 inclusive and bound exclusive.

The method you are using now returns a number between 0 inclusive and 1 exclusive. Then you are casting the result to an int . It seems likely that you are not getting the kind of distribution that you expect because of the generator that you are using.

as far as I can tell, you are returning edges.size() not randEdge . assuming you're not changing the edges array, you will always return the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM