Home > Back-end >  Generate a random integer on an interval
Generate a random integer on an interval

Time:09-14

So I have this class called Organism:

public class Organism implements Comparable{

    // Represents the organisms guess for the unknown string
    String value;
    // String the organism is trying to guess
    String goalString;
    int n;

    public Organism(String goalString) {
        this.goalString = goalString;
        this.value = goalString;
    }

    public Organism(String value, String goalString, int n) {
        this.goalString = goalString;
        this.value = value;
        this.n = n;
    }

    public int fitness(){
        // Represents the fitness of the organism
        int count = 0;

        for(int i = 0; i < goalString.length(); i  ) {
            if(value.charAt(i) == goalString.charAt(i)) {
                count   ;
            }
        }
        return count;
    }

    public Organism[] mate(Organism other) {
        // Generate a random integer from [0, n-1]
        int crossOver;



        return new Organism[0];
    }

    @Override
    public int compareTo(Object o) {

        return 0;
    }

    public void mutate(double mutateProb) {

    }

    @Override
    public String toString() {
        return "Value: "   value   "    "   "Goal: "   goalString   "    "   "Fitness: "   fitness();
    }


    public String getValue() {
        return value;
    }

    public String getGoalString() {
        return goalString;
    }

    public int getN() {
        return n;
    }

}

Inside of the mate method I need to generate a random integer on the interval [0, n-1] where n is the length of value and goalString. I then need to store that inside of the crossOver variable inside of the mate method. What would be the best way to do that?

CodePudding user response:

This should do the thing:

int n = other.getValue().length()   other.getGoalString().length();
Random rand = new Random();
int crossOver = rand.nextInt(n);

If you meant n should be the sum of the value and goalStrng of the current (this) object, simply remove the other. or replace it with this..

All have to be placed in the public Organism[] mate(Organism other) method.

  • Related