01 /*
02 * Java Genetic Algorithm Library (jenetics-2.0.2).
03 * Copyright (c) 2007-2014 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;
21
22 import static java.lang.String.format;
23 import static java.util.Objects.requireNonNull;
24
25 import java.util.Random;
26
27 import org.jenetics.internal.util.HashBuilder;
28
29 import org.jenetics.util.RandomRegistry;
30
31 /**
32 * The Monte Carlo selector selects the individuals from a given population
33 * randomly. This selector can be used to measure the performance of a other
34 * selectors. In general, the performance of a selector should be better than
35 * the selection performance of the Monte Carlo selector.
36 *
37 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
38 * @since 1.0
39 * @version 2.0 — <em>$Date: 2014-03-12 $</em>
40 */
41 public final class MonteCarloSelector<
42 G extends Gene<?, G>,
43 C extends Comparable<? super C>
44 >
45 implements Selector<G, C>
46 {
47
48 public MonteCarloSelector() {
49 }
50
51 @Override
52 public Population<G, C> select(
53 final Population<G, C> population,
54 final int count,
55 final Optimize opt
56 ) {
57 requireNonNull(population, "Population");
58 requireNonNull(opt, "Optimization");
59 if (count < 0) {
60 throw new IllegalArgumentException(format(
61 "Selection count must be greater or equal then zero, but was %d.",
62 count
63 ));
64 }
65
66 final Population<G, C> selection = new Population<>(count);
67
68 if (count > 0) {
69 final Random random = RandomRegistry.getRandom();
70 final int size = population.size();
71 for (int i = 0; i < count; ++i) {
72 final int pos = random.nextInt(size);
73 selection.add(population.get(pos));
74 }
75 }
76
77 return selection;
78 }
79
80 @Override
81 public int hashCode() {
82 return HashBuilder.of(getClass()).value();
83 }
84
85 @Override
86 public boolean equals(final Object obj) {
87 return obj == this || obj instanceof MonteCarloSelector<?, ?>;
88 }
89
90 @Override
91 public String toString() {
92 return format("%s", getClass().getSimpleName());
93 }
94
95 }
|