package algorithm.binary; import java.util.ArrayList; import java.util.List; import api.AlgorithmFrameworkFlex; import utility.StringFormat; public class GreedyAlgorithm extends AlgorithmFrameworkFlex{ private int problemSize = 0; private boolean moreInformation = true; @Override protected Individual executeAlgo() { Individual best = new Individual(); best.position = extractPositionAndAccess(); println("Bit-Array_length: " + best.position.size()); best.fitness = evaluatePosition(best.position); List runList = new ArrayList(); runList.add(best.fitness); println("Start with: " + StringFormat.doubleFixedPlaces(2, best.fitness)); problemSize = best.position.size(); List indexList = new ArrayList(); for(int index = 0; index < problemSize; index++) { indexList.add(index); } Individual bestAfterRound = new Individual(best); for(int round = 0; round < problemSize; round++) { Individual startInThisRound = new Individual(bestAfterRound); Individual bestInThisRound = new Individual(); int indexToRemove = -1; bestInThisRound.fitness = Float.MAX_VALUE; for(Integer i : indexList) { boolean actualValue = startInThisRound.position.get(i); startInThisRound.position.set(i, !actualValue); double fitness = evaluatePosition(startInThisRound.position); if(fitness < bestInThisRound.fitness) { bestInThisRound = new Individual(startInThisRound); bestInThisRound.fitness = fitness; indexToRemove = i; } startInThisRound.position.set(i, actualValue); } if(cancel) return null; bestAfterRound = bestInThisRound; println("Fitness: " + bestInThisRound.fitness + "FlippedIndex = " + indexToRemove + "(" +indexList.size() + ")"); if(bestAfterRound.fitness < best.fitness) { best = bestAfterRound; } indexList.remove(Integer.valueOf(indexToRemove)); } return best; } protected void println(String value) { if(moreInformation)console.println(value); } @Override protected int getProgressBarMaxCount() { return (problemSize * (problemSize + 1)) / 2; } @Override protected String algoInformationToPrint() { return "NoParameter"; } @Override protected String plottFileName() { return "plottGreedy.txt"; } }