GreedyAlgorithm.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package algorithm.binary;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import api.AlgorithmFrameworkFlex;
  5. import utility.StringFormat;
  6. public class GreedyAlgorithm extends AlgorithmFrameworkFlex{
  7. private int problemSize = 0;
  8. private boolean moreInformation = true;
  9. @Override
  10. protected Individual executeAlgo() {
  11. Individual best = new Individual();
  12. best.position = extractPositionAndAccess();
  13. println("Bit-Array_length: " + best.position.size());
  14. best.fitness = evaluatePosition(best.position);
  15. List<Double> runList = new ArrayList<Double>();
  16. runList.add(best.fitness);
  17. println("Start with: " + StringFormat.doubleFixedPlaces(2, best.fitness));
  18. problemSize = best.position.size();
  19. List<Integer> indexList = new ArrayList<Integer>();
  20. for(int index = 0; index < problemSize; index++)
  21. {
  22. indexList.add(index);
  23. }
  24. Individual bestAfterRound = new Individual(best);
  25. for(int round = 0; round < problemSize; round++)
  26. {
  27. Individual startInThisRound = new Individual(bestAfterRound);
  28. Individual bestInThisRound = new Individual();
  29. int indexToRemove = -1;
  30. bestInThisRound.fitness = Float.MAX_VALUE;
  31. for(Integer i : indexList) {
  32. boolean actualValue = startInThisRound.position.get(i);
  33. startInThisRound.position.set(i, !actualValue);
  34. double fitness = evaluatePosition(startInThisRound.position);
  35. if(fitness < bestInThisRound.fitness) {
  36. bestInThisRound = new Individual(startInThisRound);
  37. bestInThisRound.fitness = fitness;
  38. indexToRemove = i;
  39. }
  40. startInThisRound.position.set(i, actualValue);
  41. }
  42. if(cancel) return null;
  43. bestAfterRound = bestInThisRound;
  44. println("Fitness: " + bestInThisRound.fitness + "FlippedIndex = " + indexToRemove + "(" +indexList.size() + ")");
  45. if(bestAfterRound.fitness < best.fitness) {
  46. best = bestAfterRound;
  47. }
  48. indexList.remove(Integer.valueOf(indexToRemove));
  49. }
  50. return best;
  51. }
  52. protected void println(String value) {
  53. if(moreInformation)console.println(value);
  54. }
  55. @Override
  56. protected int getProgressBarMaxCount() {
  57. return (problemSize * (problemSize + 1)) / 2;
  58. }
  59. @Override
  60. protected String algoInformationToPrint() {
  61. return "NoParameter";
  62. }
  63. @Override
  64. protected String plottFileName() {
  65. return "plottGreedy.txt";
  66. }
  67. }