01 /*
02 * Java Genetic Algorithm Library (jenetics-6.1.0).
03 * Copyright (c) 2007-2020 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 ([email protected])
19 */
20 package io.jenetics;
21
22 import static java.lang.String.format;
23 import static java.util.Objects.requireNonNull;
24
25 import java.util.Random;
26
27 import io.jenetics.util.ISeq;
28 import io.jenetics.util.MSeq;
29 import io.jenetics.util.RandomRegistry;
30 import io.jenetics.util.Seq;
31
32 /**
33 * The Monte Carlo selector selects the individuals from a given population
34 * randomly. This selector can be used to measure the performance of a other
35 * selectors. In general, the performance of a selector should be better than
36 * the selection performance of the Monte Carlo selector.
37 *
38 * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
39 * @since 1.0
40 * @version 5.0
41 */
42 public final class MonteCarloSelector<
43 G extends Gene<?, G>,
44 C extends Comparable<? super C>
45 >
46 implements Selector<G, C>
47 {
48
49 public MonteCarloSelector() {
50 }
51
52 @Override
53 public ISeq<Phenotype<G, C>> select(
54 final Seq<Phenotype<G, C>> population,
55 final int count,
56 final Optimize opt
57 ) {
58 requireNonNull(population, "Population");
59 requireNonNull(opt, "Optimization");
60 if (count < 0) {
61 throw new IllegalArgumentException(format(
62 "Selection count must be greater or equal then zero, but was %d.",
63 count
64 ));
65 }
66
67 final MSeq<Phenotype<G, C>> selection;
68 if (count > 0 && !population.isEmpty()) {
69 selection = MSeq.ofLength(count);
70 final Random random = RandomRegistry.random();
71 final int size = population.size();
72
73 for (int i = 0; i < count; ++i) {
74 final int pos = random.nextInt(size);
75 selection.set(i, population.get(pos));
76 }
77 } else {
78 selection = MSeq.empty();
79 }
80
81 return selection.toISeq();
82 }
83
84 @Override
85 public String toString() {
86 return format("%s", getClass().getSimpleName());
87 }
88
89 }
|