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