OnesCounting.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-3.7.0).
03  * Copyright (c) 2007-2016 Franz Wilhelmstötter
04  *
05  * Licensed under the Apache License, Version 2.0 (the "License");
06  * you may not use this file except in compliance with the License.
07  * You may obtain a copy of the License at
08  *
09  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author:
18  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19  */
20 package org.jenetics.tool.problem;
21 
22 import java.util.function.Function;
23 
24 import org.jenetics.BitChromosome;
25 import org.jenetics.BitGene;
26 import org.jenetics.Genotype;
27 import org.jenetics.engine.Codec;
28 import org.jenetics.engine.Engine;
29 import org.jenetics.engine.EvolutionResult;
30 import org.jenetics.engine.Problem;
31 import org.jenetics.util.ISeq;
32 
33 /**
34  * Full Ones-Counting example.
35  *
36  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
37  @version 3.6
38  @since 3.5
39  */
40 public class OnesCounting implements Problem<ISeq<BitGene>, BitGene, Integer> {
41 
42     private final int _length;
43     private final double _onesProbability;
44 
45     /**
46      * Create a new Ones-Counting example with the given parameters.
47      *
48      @param length the length of the ones-vector
49      @param onesProbability the probability of ones in the created vector
50      */
51     public OnesCounting(final int length, final double onesProbability) {
52         _length = length;
53         _onesProbability = onesProbability;
54     }
55 
56     @Override
57     public Function<ISeq<BitGene>, Integer> fitness() {
58         return genes -> (int)genes.stream().filter(BitGene::getBit).count();
59     }
60 
61     @Override
62     public Codec<ISeq<BitGene>, BitGene> codec() {
63         return Codec.of(
64             Genotype.of(BitChromosome.of(_length, _onesProbability)),
65             gt -> gt.getChromosome().toSeq()
66         );
67     }
68 
69     public static void main(final String[] args) {
70         final OnesCounting problem = new OnesCounting(150.13);
71         final Engine<BitGene, Integer> engine = Engine.builder(problem).build();
72 
73         final ISeq<BitGene> result = problem.codec().decoder().apply(
74             engine.stream()
75                 .limit(10)
76                 .collect(EvolutionResult.toBestGenotype())
77         );
78 
79         System.out.println(result);
80     }
81 
82 }