У меня есть функция фитнеса как часть лаборатории, и я хочу применить ее к набору «веса» (веса в масштабах). Я создал массив и сохранил в нем некоторые значения. Я создал случайные бинарные строки (которые имеют «X» в конце, чтобы генерировать случайные значения), которые я также хочу применить функцию пригодности; Тем не менее, проблема, с которой у меня возникает, заключается в том, что функция фитнеса всегда возвращает значение 0. Я что -то упускаю здесь?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 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();
}}
< /code>
Основной метод (в отдельном классе): < /p>
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 weights = new ArrayList();
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);
}}
< /code>
cs2004 Класс: < /p>
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 ReadNumberFile(String filename)
{
ArrayList res = new ArrayList();
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);
}}
< /code>
После запуска случайные двоичные строки работают совершенно хорошо, но функция фитнеса не может измениться с 0. Вот пример вывода: < /p>
011100
111010
001110
111011
001000
010101
001010
100011
110100
011001
[1.0, 2.0, 3.0, 4.0, 10.0]
Fitness: 0.0
< /code>
Большое спасибо всем за ваше время.
stefanos.
Подробнее здесь: https://stackoverflow.com/questions/136 ... ion-scales
Java Fitness Function - весы ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Основы функции - Function Function Function, выходящая из INT, более 99 [закрыто]
Anonymous » » в форуме Python - 0 Ответы
- 32 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Есть ли способ интегрировать мои весы с моим POS-приложением ASP.NET? [закрыто]
Anonymous » » в форуме C# - 0 Ответы
- 23 Просмотры
-
Последнее сообщение Anonymous
-