tutorials.de Buch-Aktion 05/2012
ERLEDIGT
NEIN
ANTWORTEN
1
ZUGRIFFE
1582
EMPFEHLEN
  • An Twitter übertragen
  • An Facebook übertragen
  1. #1
    Registriert seit
    Jun 2002
    Ort
    Saarbrücken (Saarland)
    Beiträge
    9.885
    Blog-Einträge
    29
    Hallo,

    hier mal eine prototypische Lösung des Rucksack Problems mit einem generischen Genetischen Algorithmus.
    Eine Erklärung zu genetischen Algorithmen findet man beispielsweise hier:
    http://de.wikipedia.org/wiki/Genetischer_Algorithmus

    Die Beispiel-Implementierung kann die kleineren / einfacheren Knappsackeingaben ohne Probleme lösen, scheitert jedoch
    an der großen 100k.txt-Eingabe von onlyfoo. Durch tuning bzw. einführen neuer Algorithmus Parameter sowie
    weiterer Problemnäherer genetischer Operatoren würde man dieses Problem sicherlich auch noch hinbekommen.

    Code java:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    
    package de.tutorials.contest.quiz15;
     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.BitSet;
    import java.util.List;
    import java.util.Random;
    import java.util.Scanner;
     
    public class GeneticEasterEggs {
     
      public static void main(String[] args) throws Exception {
        System.out.println("GeneticEasterEggs");
        new GeneticEasterEggs().solve();
      }
     
     
      void solve() throws Exception {
        SweetProblem problem = readInput("easterEggs.dat");
     
        GeneticSolver<BitSet> geneticSolver = new GeneticSolver<BitSet>();
     
        SolutionFitness<BitSet> best = geneticSolver.solve(problem);
     
        System.out.println(best);
     
        int mass = 0;
        int kcal = 0;
        int takenSweets = 0;
        for (int i = 0; i < problem.sweets.size(); i++) {
          if (best.solution.get(i)) {
            Sweet sweet = problem.sweets.get(i);
            mass += sweet.weight;
            kcal += sweet.kcal;
            System.out.print((takenSweets++ > 0 ? "," : "") + sweet.name);
          }
        }
        
        System.out.println();
        System.out.println("Masse: " + mass);
        System.out.println("Nährwert: " + kcal);
      }
     
     
      SweetProblem readInput(String fileLocation) throws FileNotFoundException {
        SweetProblem problem = new SweetProblem();
        Scanner scanner = new Scanner(new File(fileLocation));
        problem.sweets = new ArrayList<Sweet>();
        problem.maxWeightInGramm = Integer.parseInt(scanner.nextLine().trim());
     
        while (scanner.hasNext()) {
          String line = scanner.nextLine();
          if ("".equals(line)) {
            break;
          }
          String name = line;
          String[] weightAndKcal = scanner.nextLine().split(" ");
          int weight = Integer.parseInt(weightAndKcal[0]);
          int kcal = Integer.parseInt(weightAndKcal[1]);
     
          problem.sweets.add(new Sweet(name, weight, kcal));
        }
        return problem;
      }
     
      static class Sweet {
        String name;
        int weight;
        int kcal;
     
     
        public Sweet(String name, int weight, int kcal) {
          this.name = name;
          this.weight = weight;
          this.kcal = kcal;
        }
      }
      
      
     
      static class SweetProblem implements Problem<BitSet>{
        List<Sweet> sweets;
        int maxWeightInGramm;
        Random randomizer = new Random();
     
     
        @Override
        public double fitness(BitSet bitSet) {
          double fitness = 0.0;
          int weight = 0;
     
          for (int i = 0, size = sweets.size(); i < size; i++) {
            if (bitSet.get(i)) {
              Sweet sweet = sweets.get(i);
              fitness += sweet.kcal;
              weight += sweet.weight;
            }
          }
     
          if (weight > maxWeightInGramm) {
            fitness = 0; // penalty for weight constraint violation
          }
     
          return fitness;
        }
     
     
        @Override
        public BitSet breed() {
          int size = sweets.size();
          BitSet bitSet = new BitSet();
          bitSet.set(randomizer.nextInt(size));
          return bitSet;
        }
     
     
        @Override
        public BitSet combine(BitSet first, BitSet second) {
          int size = sweets.size();
          int crossOverIndex = randomizer.nextInt(size);
     
          BitSet combination = new BitSet();
     
          for (int i = 0; i < crossOverIndex; i++) {
            if (first.get(i)) {
              combination.set(i);
            }
          }
     
          for (int i = crossOverIndex; i < size; i++) {
            if (second.get(i)) {
              combination.set(i);
            }
          }
     
          return combination;
        }
     
     
        @Override
        public BitSet mutate(BitSet individual) {
          int size = sweets.size();
          BitSet mutation = new BitSet();
          mutation.or(individual);
          mutation.flip(randomizer.nextInt(size));
          return mutation;
        }
     
      }
     
      static class Population<TSolution> {
        List<TSolution> solutions = new ArrayList<TSolution>();
     
     
        public Population() {
        }
     
     
        public Population(SolutionFitness<TSolution>[] topElite) {
          for (SolutionFitness<TSolution> soluationFitness : topElite) {
            solutions.add(soluationFitness.solution);
          }
        }
     
     
        public int size() {
          return solutions.size();
        }
     
     
        TSolution get(int index) {
          return solutions.get(index);
        }
     
     
        void add(TSolution solution) {
          solutions.add(solution);
        }
      }
     
      static interface Problem<TSolution> extends FitnessFunction<TSolution>, Breeder<TSolution>, Combiner<TSolution>, Mutator<TSolution>{
      }
      
      static interface FitnessFunction<TSolution> {
        double fitness(TSolution solution);
      }
     
      static interface Breeder<TSolution> {
        TSolution breed();
      }
     
      static interface Combiner<TSolution> {
        TSolution combine(TSolution first, TSolution second);
      }
     
      static interface Mutator<TSolution> {
        TSolution mutate(TSolution solution);
      }
     
      static class SolutionFitness<TSolution> implements Comparable<SolutionFitness<TSolution>> {
        TSolution solution;
        double fitness;
     
     
        public SolutionFitness(TSolution solution, double fitness) {
          this.solution = solution;
          this.fitness = fitness;
        }
     
     
        @Override
        public int compareTo(SolutionFitness<TSolution> that) {
          return -Double.compare(this.fitness, that.fitness);
        }
      }
     
      static class GeneticSolver<TSolution> {
        Breeder<TSolution> breeder;
        Combiner<TSolution> combiner;
        Mutator<TSolution> mutator;
        FitnessFunction<TSolution> fitnessFunction;
        Random randomizer = new Random();
     
        int populationSize = 500;
        int maxIterations = 100;
        int maxIterationsWithNoImprovement = maxIterations;
        double elite = 0.3;
        double mutationProbability = 0.4;
     
     
        public SolutionFitness<TSolution> solve(Problem<TSolution> problem) {
     
          init(problem);
     
          System.out.println("Starting genetic search...");
     
          SolutionFitness<TSolution> currentBest = null;
     
          Population<TSolution> currentPopulation = generatePopulation();
          int eliteCount = (int) (populationSize * elite);
     
          int iterationsWithNoImprovement = 0;
     
          for (int i = 0; i < maxIterations; i++) {
            SolutionFitness<TSolution>[] solutionFitnesses = evaluate(currentPopulation);
            SolutionFitness<TSolution>[] rankedSolutions = computeRankingBestSolutionsFirst(solutionFitnesses);
            SolutionFitness<TSolution>[] topElite = takeTopEliteSolutions(eliteCount, rankedSolutions);
            
            currentPopulation = new Population<TSolution>(topElite);
     
            while (currentPopulation.size() < populationSize) {
              TSolution candidate = applyGeneticOperators(topElite);
              currentPopulation.add(candidate);
            }
     
            SolutionFitness<TSolution> nextBest = topElite[0];
     
            if (currentBest != null) {
              if (currentBest.fitness == nextBest.fitness) {
                iterationsWithNoImprovement++;
              } else {
                iterationsWithNoImprovement = 0;
              }
     
              if (iterationsWithNoImprovement > maxIterationsWithNoImprovement) {
                System.out.println("No improvement for " + maxIterationsWithNoImprovement + " iterations");
                break;
              }
            }
     
            currentBest = nextBest;
            // System.out.println("Current best: " + currentBest.fitness
            // + " " + best.individual
            // );
          }
     
          return currentBest;
        }
     
     
        private SolutionFitness<TSolution>[] takeTopEliteSolutions(int eliteCount,
          SolutionFitness<TSolution>[] rankedSolutions) {
          return Arrays.copyOf(rankedSolutions, eliteCount);
        }
     
     
        void init(Problem<TSolution> problem) {
          this.breeder = problem;
          this.combiner = problem;
          this.mutator = problem;
          this.fitnessFunction = problem;
        }
     
     
        TSolution applyGeneticOperators(SolutionFitness<TSolution>[] topElite) {
          TSolution candidate;
          if (randomizer.nextDouble() < mutationProbability) {
            TSolution mutationCandidate = topElite[randomizer.nextInt(topElite.length)].solution;
            TSolution mutation = mutator.mutate(mutationCandidate);
            candidate = mutation;
          } else {
            TSolution firstCandidate = topElite[randomizer.nextInt(topElite.length)].solution;
            TSolution secondCandidate = topElite[randomizer.nextInt(topElite.length)].solution;
            TSolution combination = combiner.combine(firstCandidate, secondCandidate);
            candidate = combination;
          }
          return candidate;
        }
     
     
        SolutionFitness<TSolution>[] computeRankingBestSolutionsFirst(SolutionFitness<TSolution>[] individualFitnesses) {
          Arrays.sort(individualFitnesses);
          return individualFitnesses;
        }
     
     
        SolutionFitness<TSolution>[] evaluate(Population<TSolution> population) {
          SolutionFitness<TSolution>[] solutionFitnesses = new SolutionFitness[populationSize];
          for (int i = 0; i < solutionFitnesses.length; i++) {
            TSolution solution = population.get(i);
            double fitness = fitnessFunction.fitness(solution);
            solutionFitnesses[i] = new SolutionFitness<TSolution>(solution, fitness);
          }
          return solutionFitnesses;
        }
     
     
        Population<TSolution> generatePopulation() {
          Population<TSolution> population = new Population<TSolution>();
          for (int i = 0; i < populationSize; i++) {
            TSolution individual = breeder.breed();
            population.add(individual);
          }
          return population;
        }
      }
     
    }

    Eingabe:
    Code :
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    500
    Nougat-Eier
    84 427
    Fondant-Eier
    150 540
    Ostereier
    189 291
    Spannungs-Eier
    63 330
    Waffeleier
    120 600
    Melker Runzelhase
    70 371
    Lynt Platinhase
    250 1360

    Ausgabe:
    Code :
    1
    2
    3
    4
    5
    6
    
    GeneticEasterEggs
    Starting genetic search...
    de.tutorials.contest.quiz15.GeneticEasterEggs$SolutionFitness@6ef0eed6
    Nougat-Eier,Spannungs-Eier,Melker Runzelhase,Lynt Platinhase
    Masse: 467
    Nährwert: 2488

    Gruß Tom
     
    Java rocks!
    How to become a good Java Programmer?
    Does IT in Java and .Net
    The only valid measurement of code quality: WTFs / minute
    Blog
    Xing
    Twitter

  2. #2
    Registriert seit
    Dec 2001
    Ort
    Bayern
    Beiträge
    5.800
    Blog-Einträge
    5
    Hey Tom,

    sehr coole Lösung! Muss ich mir nachher mal in Ruhe genauer anschauen…

    Grüße,
    Matthias
     
    „Gib einem Menschen einen Fisch, und er wird für einen Tag satt. Lehre ihn Fischen, und er wird ein Leben lang satt.“
    “For every complex problem, there is an answer that is short, simple and wrong.”
    “Pessimism is safe, but optimism is a lot faster!”


    Aktuelles Coding Quiz: #17 - Wörter kreuz und quer

Thema nicht erledigt

Ähnliche Themen

  1. [Quiz #13] Thomas Darimont (Java)
    Von Thomas Darimont im Forum Archiv
    Antworten: 0
    Letzter Beitrag: 10.01.10, 23:28
  2. [Quiz #9] Thomas Darimont (Java)
    Von Thomas Darimont im Forum Archiv
    Antworten: 0
    Letzter Beitrag: 21.07.09, 23:35
  3. [QUIZ#7] Thomas Darimont (Java)
    Von Thomas Darimont im Forum Archiv
    Antworten: 1
    Letzter Beitrag: 08.12.08, 09:45
  4. [QUIZ #2] Thomas Darimont (Java)
    Von Thomas Darimont im Forum Archiv
    Antworten: 0
    Letzter Beitrag: 28.09.08, 14:08
  5. [QUIZ#1] Thomas Darimont (Java)
    Von Thomas Darimont im Forum Archiv
    Antworten: 2
    Letzter Beitrag: 22.09.08, 14:13