ElitistSelector.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;
21 
22 import static java.lang.Math.max;
23 
24 import org.jenetics.Gene;
25 import org.jenetics.Optimize;
26 import org.jenetics.Population;
27 import org.jenetics.Selector;
28 import org.jenetics.TournamentSelector;
29 import org.jenetics.TruncationSelector;
30 
31 /**
32  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
33  @version 3.4
34  @since 3.4
35  */
36 public class ElitistSelector<
37     extends Gene<?, G>,
38     extends Comparable<? super C>
39 >
40     implements Selector<G, C>
41 {
42     private final TruncationSelector<G, C> _elitist = new TruncationSelector<>();
43     private final TournamentSelector<G, C> _rest = new TournamentSelector<>(3);
44 
45     @Override
46     public Population<G, C> select(
47         final Population<G, C> population,
48         final int count,
49         final Optimize opt
50     ) {
51         return population.isEmpty() || count <= 0
52             new Population<>(0)
53             : append(
54                 _elitist.select(population, 1, opt),
55                 _rest.select(population, max(0, count - 1), opt));
56     }
57 
58     private Population<G, C> append(
59         final Population<G, C> p1,
60         final Population<G, C> p2
61     ) {
62         p1.addAll(p2);
63         return p1;
64     }
65 }