首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Fitness函数- Scales

Java Fitness函数- Scales
EN

Stack Overflow用户
提问于 2012-11-30 00:30:51
回答 1查看 2.6K关注 0票数 2

我有一个适应度函数作为实验室的一部分,并希望将其应用于一组“权重”(ArrayList权重)。我已经创建了数组,并在其中存储了一些值。我已经创建了随机二进制字符串(它的末尾有一个'x‘,以便生成随机值),我希望也对其应用适应度函数;然而,我遇到的问题是适应度函数总是返回值0。我是不是漏掉了什么?

适应度函数如下:

代码语言:javascript
复制
import java.util.*;
public class ScalesSolution{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)

public ScalesSolution(String s)
{
    boolean ok = true;
    int n = s.length();
    for(int i=0;i<n;++i)
    {
        char si = s.charAt(i);
        if (si != '0' && si != '1') ok = false;
    }
    if (ok)
    {
        scasol = s;
    }
    else
    {
        scasol = RandomBinaryString(n);
    }
}

private static String RandomBinaryString(int n)
{
    String s = new String();
    //Code goes here
    //Create a random binary string of just ones and zeros of length n
    for(int i = 0; i < n; i++){
        int x = CS2004.UI(0,1);
            if(x == 0){
                System.out.print(s + '0');
            }
            else if(x == 1){
                System.out.print(s + '1');
            }
    }
    return(s);
}

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();
    double lhs = 0.0, rhs = 0.0;
    if (n > weights.size()) return(-1);

    for(int i = 0; i < n; i++){
        if(scasol.charAt(i) == 0){
            lhs += weights.get(i);
        }
        else{
            rhs += weights.get(i);
        }
    }       
    //Code goes here
    //Check each element of scasol for a 0 (lhs) and 1 (rhs) add the weight wi
    //to variables lhs and rhs as appropriate
    return(Math.abs(lhs-rhs));
}

//Display the string without a new line
public void print()
{
    System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
    print();
    System.out.println();
}}

Main方法(在单独的类中):

代码语言:javascript
复制
import java.util.ArrayList;
public class Lab8 {

public static void main(String args[])
{
    for(int i = 0; i < 10; i++){
        ScalesSolution s = new ScalesSolution("10101x");
        s.println();
    }


    ArrayList<Double> weights = new ArrayList<Double>();
    weights.add(1.0);
    weights.add(2.0);
    weights.add(3.0);
    weights.add(4.0);
    weights.add(10.0);
    System.out.println();
    System.out.println(weights);
    System.out.print("Fitness: ");

    double fitness = ScalesSolution.ScalesFitness(weights);
    System.out.println(fitness);

}}

CS2004类:

代码语言:javascript
复制
import java.util.*;
import java.io.*;

//Some useful code that we will probably reuse in later laboratories...
public class CS2004 
{
//Shared random object
static private Random rand;
//Create a uniformly distributed random integer between aa and bb inclusive
static public int UI(int aa,int bb)
{
    int a = Math.min(aa,bb);
    int b = Math.max(aa,bb);
    if (rand == null) 
    {
        rand = new Random();
        rand.setSeed(System.nanoTime());
    }
    int d = b - a + 1;
    int x = rand.nextInt(d) + a;
    return(x);
}
//Create a uniformly distributed random double between a and b inclusive
static public double UR(double a,double b)
{
    if (rand == null) 
    {
        rand = new Random();
        rand.setSeed(System.nanoTime());
    }
    return((b-a)*rand.nextDouble()+a);
}
//This method reads in a text file and parses all of the numbers in it
//This code is not very good and can be improved!
//But it should work!!!
//It takes in as input a string filename and returns an array list of Doubles
static public ArrayList<Double> ReadNumberFile(String filename)
{
    ArrayList<Double> res = new ArrayList<Double>();
    Reader r;
    try
    {
        r = new BufferedReader(new FileReader(filename));
        StreamTokenizer stok = new StreamTokenizer(r);
        stok.parseNumbers();
        stok.nextToken();
        while (stok.ttype != StreamTokenizer.TT_EOF) 
        {
            if (stok.ttype == StreamTokenizer.TT_NUMBER)
            {
                res.add(stok.nval);
            }
            stok.nextToken();
        }
    }
    catch(Exception E)
    {
        System.out.println("+++ReadFile: "+E.getMessage());
    }
    return(res);
}}

一旦运行,随机二进制字符串就可以很好地工作,但适应度函数无法从0更改。以下是示例输出:

代码语言:javascript
复制
011100
111010
001110
111011
001000
010101
001010
100011
110100
011001

[1.0, 2.0, 3.0, 4.0, 10.0]
Fitness: 0.0

非常感谢大家抽出时间。斯蒂芬斯。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-30 00:55:58

调用ScalesFitness时,scasol似乎为空。在RandomBinaryString方法中,您实际上从未构造过s,而只是将其打印出来。您应该使用s += '0';,而不是System.out.print(s+'0')和另一行。

既然这看起来像是一个练习,剩下的就留给你了,但这里有个提示给你:不要让一个函数做比它应该做的更多的事情(比如打印出它的结果),否则,它可能看起来像是函数集实际上是在工作,而实际上它并不是。

在本例中,看起来一切正常,因为它看起来像s.println()函数,实际打印scasol,但实际上,scasol是空的,并且RandomBinaryString方法实际上正在执行打印。

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

https://stackoverflow.com/questions/13630288

复制
相关文章

相似问题

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