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