开发者

Java If Statement

I have written some code in Java which tests the fitness of two solutions.

I am looking to then compare the two solutions and keep the one which has the best fitnes开发者_运维知识库s and to discard the other.

For example:

if(fitness1 < fitness2)
    keep fitness1 and discard/ignore fitness2
else
    keep fitness2 and discard/ignore fitness1

How would I go about achieving this? Eventually I hope to have a list (size n) of the best fitness levels. I imagine that I would have to add the best fitness in each iteration to a list of some type?


best = (fitness1 < fitness2) ? fitness1 : fitness2;

?: ternary operator may be useful in this kind of decision making process.


I'd say, create an ArrayList<Double> to keep the best values in and use this:

arrayList.add((fitness1 < fitness2) ? fitness1 : fitness2);

That way you'll have a list of the best values.


If your end goal is to have a list of the "top n fitness levels", you'll probably have a list of them coming in, right?

If that's the case, just leverage the capabilities of List:

// takes a list of Doubles, returns 'top' levels
public List<Double> getTopN(List<Double> allLevels, int top) {
    List<Double> sorted = new ArrayList<Double>(allLevels); // defensive copy
    Collections.sort(sorted, new Comparator<Double>() {
        @Override
        public int compare(Double left, Double right) {
            return left.compareTo(right); // assumes no null entries
        }
    });

    return sorted.subList(0, Math.min(sorted.size(), top));
}


Introduce another variable.

type bestFitness

if(fitness1 < fitness2){
   bestFitness = fitness1;
}else{
   bestFitness = fitness2;
}

Then discard both fitness1, fitness2

Or use Math.min


Assuming the fitness is an int

int fitness1 = 5;
int fitness2 = 10;

int bestFit = bestFit(fitness1, fitness2);

//nothing needs to be done to explicitly discard fitness2.  Just keep using bestFit
//and let the GC worry about discarding stuff for you

public static int bestFit(int f1, int f2) { 

   return f1 > f2 ? f1 : f2

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜