爬山码 - 随机突变

时间:2013-01-11 11:41:05

标签: java hill-climbing

此代码应该比较两个拟合,使用最好的一个来找到解决方案,然后在下一次迭代中使用最好的一个。然而,我得到的问题是它只是使用最新的健身,无论它是大还是小。如果我的代码中有任何错误,任何人都可以帮我发现,谢谢!

这有点难以解释,所以如果有人需要更多澄清,请问我会发布我的整个项目,但我相信错误与这一小段代码有关:

public static ScalesSolution RMHC(ArrayList<Double> weights, int n, int iter) {
    ScalesSolution sol = new ScalesSolution(n);
    ScalesSolution oldSol = new ScalesSolution(sol.GetSol());
    for (int i = 0; i < iter; i++) {
        System.out.println("Iteration number: " + i);
        System.out.println("Old Solution : ");
        oldSol.println();
        double f = oldSol.ScalesFitness(weights);
        System.out.println("Old Fitness: ");
        System.out.println(f);
        // the new solution after copying the string from scalesolution
        sol.SmallChange();
        System.out.println("New Solution : ");
        sol.println();
        double f1 = sol.ScalesFitness(weights);
        System.out.println("New Fitness: ");
        System.out.println(f1);
        if (oldSol.ScalesFitness(weights) > sol.ScalesFitness(weights)) {               
            oldSol = new ScalesSolution(sol.GetSol());
        }
    }
    return (oldSol);
}

这是SmallChange:

public void SmallChange() {
    int n = scasol.length();
    Random rand = new Random();
    int p = (rand.nextInt(n));
    String x;

    x = scasol.substring(0, p);
    if (scasol.charAt(p) == '0') {
        x += '1';
    } else {
        x += '0';
    }
    x += scasol.substring(p + 1, n);
    scasol = x;
}

这是ScalesFitness和ScalesSolution:

public ScalesSolution(int n) {
    scasol = RandomBinaryString(n);
}

// This is the fitness function for the Scales problem
// This function returns -1 if the number of weights is less than the size of the current solution 
// Exercise 3

public static double ScalesFitness(ArrayList<Double> weights) {
    int n = scasol.length();                // Assigns the length of scasol to n
    double lhs = 0.0;                       //  Initialises lhs to 0.0, type double
    double rhs = 0.0;                       //  Initialises rhs to 0.0, type double
    if (n > weights.size())                 // If statement, compares n and weight size
        return (-1);                        // Returns -1 when the if statement is true

    // Code goes here
    for (int i = 0; i < n; i++) {           // For loop which goes from i=0 to n
        if (scasol.charAt(i) == '0') {      // If statement which checks if the character at position i is equal to a 0
            lhs += weights.get(i);          // Adds weight at position i to lhs
        } else {                            // If the character in position i is not a 0 do the following
            rhs += weights.get(i);          // Adds the weight at position i to rhs
        }
    }
    return (Math.abs(lhs - rhs));           // Calculates the absolute value of lhs-rhs and returns the value
}

0 个答案:

没有答案