1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- 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 = false;
-
-
- public GreedyAlgorithm() {
- super();
- addBooleanParameter("More Information", moreInformation, booleanValue -> moreInformation = booleanValue);
- }
-
-
-
-
- @Override
- protected Individual executeAlgo() {
- Individual best = new Individual();
- best.position = extractPositionAndAccess();
- println("Bit-Array_length: " + best.position.size());
- best.fitness = evaluatePosition(best.position);
- List<Double> runList = new ArrayList<Double>();
- runList.add(best.fitness);
- println("Start with: " + StringFormat.doubleFixedPlaces(2, best.fitness));
- problemSize = best.position.size();
-
-
- List<Integer> indexList = new ArrayList<Integer>();
- 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;
- }
- runList.add(best.fitness);
- indexList.remove(Integer.valueOf(indexToRemove));
- }
- this.runList = runList;
- console.println("Fitness: " + best.fitness);
- return best;
- }
-
-
- protected void println(String value) {
- if(moreInformation)console.println(value);
- }
-
- @Override
- protected int getProgressBarMaxCount() {
- List<Boolean> best = extractPositionAndAccess();
- problemSize = best.size();
- return ((problemSize * (problemSize + 1)) / 2) * rounds;
- }
-
- @Override
- protected String algoInformationToPrint() {
- return "NoParameter";
- }
- @Override
- protected String plottFileName() {
- return "plottGreedy.txt";
- }
- }
|