2011-03-14 81 views
0

我有一個健身功能作爲實驗室的一部分,並希望將其應用於一組'權重'(ArrayList權重)。我創建了該數組並在其中存儲了一些值。我創建了隨機二進制字符串(最後爲了生成隨機值而在結尾處有一個'x'),我也希望將這些字符串應用於適應度函數;然而,我遇到的問題是健身功能始終返回值0.我在這裏錯過了什麼?Java健身功能不起作用

適應度函數如下:

public static double scalesFitness(ArrayList<Double> weights){ 
    if (scasol.length() > weights.size()) return(-1); 
    double lhs = 0.0,rhs = 0.0; 

    double L = 0.0; 
    double R = 0.0; 

    for(int i = 0; i < scasol.length(); i++){ 
     if(scasol.charAt(i) == '0'){ 
     L = L += 0; 
    } 
    else if(scasol.charAt(i) == '1'){ 
     R = R += 1; 
    } 
    }//end for 

    int n = scasol.length(); 

    return(L-R); 

} 

隨機二進制字符串方法:

private static String RandomBinaryString(int n){ 
    String s = new String(); 

    for(int i = 0; i <= n; i++){ 
     int y = CS2004.UI(0,1); 
      if(y == 0){ 
       System.out.print(s + '0'); 
      } 
      else if(y == 1){ 
       System.out.print(s + '1'); 
      } 
    } 

    return(s); 
} 

主要方法(在​​單獨的類):

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.print("Fitness: "); 
    System.out.print(ScalesSolution.scalesFitness(weights)); 
} 

一旦運行,則隨機二進制字符串工作得很好,但適應度函數無法從0改變。下面是一個示例輸出:

1101100 
1100111 
0001111 
1001010 
1110000 
0011111 
1100111 
1011001 
0000110 
1000000 

Fitness: 0.0 

如果您希望爲整個班級編碼,請讓我知道。

非常感謝你的時間。

米克。

+0

如果這是家庭作業,你應該包括作業標籤。 – Greg 2011-03-14 20:02:05

回答

2

在我看來,你總是從RandomBinaryString()返回一個空白字符串 - 你打印出一些數字,但從來沒有實際追加它們。使用s = s+'0',或s += '0',或s.concat("0"),或使用StringBuilder,等...

我假設scasol是你的二進制字符串,所以這是空的,那麼沒有在你的for循環被調用一次,所以L和R都保持在0.0,而你最終返回0.0。

+0

謝謝,我試過了,但它似乎沒有工作。是的,scasol是我的二進制字符串。我注意到,如果我將以下內容更改爲< from >,則每次產生-1.0而不是0.0。 '公共靜態雙scalesFitness(ArrayList的權重) \t {\t \t \t如果(scasol.length()> weights.size())回報(-1);'難道這是某種程度上影響呢? – MusTheDataGuy 2011-03-14 20:11:52

+0

@Mick - 在這種情況下獲得-1是有意義的,如果scasol是一個空白字符串。你能發佈ScalesSolution構造函數的代碼嗎? – DHall 2011-03-14 20:15:21

+0

我剛剛意識到's.concat(「0」)本身不會做任何事情。確保你使用s = s +'0'或s + ='0'或s = s.concat(「0」)來爲s賦值。剩下的代碼應該可以工作,還要確保權重列表中的數字與種子字符串中的字符數量相同。 – DHall 2011-03-14 20:43:17

0

你的隨機字符串RandomBinaryString只能打印's'它永遠不會改變它,所以函數的總和等於返回'新的String()'。

另一個問題'L = L + = 0'是多餘的。它與L = 0相同。總是。

'R = R + = 1' 也是冗餘的,它是相同的R + = 1

0

@DHall代碼scasol構造:

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

如果這是幫助不我可以發佈該課程的代碼。

謝謝。

米克。