001 /*
002 * Java Genetic Algorithm Library (jenetics-4.3.0).
003 * Copyright (c) 2007-2018 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 * Author:
018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019 */
020 package io.jenetics;
021
022 import static java.lang.String.format;
023 import static io.jenetics.internal.util.Hashes.hash;
024 import static io.jenetics.util.RandomRegistry.getRandom;
025
026 import java.io.Serializable;
027 import java.util.Random;
028
029 import io.jenetics.internal.math.random;
030 import io.jenetics.util.ISeq;
031 import io.jenetics.util.IntRange;
032 import io.jenetics.util.MSeq;
033 import io.jenetics.util.Mean;
034
035 /**
036 * NumericGene implementation which holds a 32 bit integer number.
037 *
038 * <p>This is a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html">
039 * value-based</a> class; use of identity-sensitive operations (including
040 * reference equality ({@code ==}), identity hash code, or synchronization) on
041 * instances of {@code IntegerGene} may have unpredictable results and should
042 * be avoided.
043 *
044 * @see IntegerChromosome
045 *
046 * @implNote
047 * This class is immutable and thread-safe.
048 *
049 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
050 * @since 2.0
051 * @version 4.3
052 */
053 public final class IntegerGene
054 implements
055 NumericGene<Integer, IntegerGene>,
056 Mean<IntegerGene>,
057 Comparable<IntegerGene>,
058 Serializable
059 {
060
061 private static final long serialVersionUID = 2L;
062
063 private final int _value;
064 private final int _min;
065 private final int _max;
066
067 /**
068 * Create a new random {@code IntegerGene} with the given value and the
069 * given range. If the {@code value} isn't within the interval [min, max],
070 * no exception is thrown. In this case the method
071 * {@link IntegerGene#isValid()} returns {@code false}.
072 *
073 * @param value the value of the gene.
074 * @param min the minimal valid value of this gene (inclusively).
075 * @param max the maximal valid value of this gene (inclusively).
076 */
077 private IntegerGene(final int value, final int min, final int max) {
078 _value = value;
079 _min = min;
080 _max = max;
081 }
082
083 @Override
084 public Integer getAllele() {
085 return _value;
086 }
087
088 @Override
089 public Integer getMin() {
090 return _min;
091 }
092
093 @Override
094 public Integer getMax() {
095 return _max;
096 }
097
098 @Override
099 public byte byteValue() {
100 return (byte)_value;
101 }
102
103 @Override
104 public short shortValue() {
105 return (short)_value;
106 }
107
108 @Override
109 public int intValue() {
110 return _value;
111 }
112
113 @Override
114 public long longValue() {
115 return _value;
116 }
117
118 @Override
119 public float floatValue() {
120 return (float)_value;
121 }
122
123 @Override
124 public double doubleValue() {
125 return _value;
126 }
127
128 @Override
129 public boolean isValid() {
130 return _value >= _min && _value <= _max;
131 }
132
133 @Override
134 public int compareTo(final IntegerGene other) {
135 return Integer.compare(_value, other._value);
136 }
137
138 @Override
139 public IntegerGene newInstance(final Integer number) {
140 return IntegerGene.of(number, _min, _max);
141 }
142
143 @Override
144 public IntegerGene newInstance(final Number number) {
145 return IntegerGene.of(number.intValue(), _min, _max);
146 }
147
148 @Override
149 public IntegerGene newInstance() {
150 return IntegerGene.of(nextInt(getRandom(), _min, _max), _min, _max);
151 }
152
153 @Override
154 public IntegerGene mean(final IntegerGene that) {
155 return IntegerGene.of(_value + (that._value - _value)/2, _min, _max);
156 }
157
158 @Override
159 public int hashCode() {
160 return hash(_value, hash(_min, hash(_max, hash(getClass()))));
161 }
162
163 @Override
164 public boolean equals(final Object obj) {
165 return obj == this ||
166 obj instanceof IntegerGene &&
167 ((IntegerGene)obj)._value == _value &&
168 ((IntegerGene)obj)._min == _min &&
169 ((IntegerGene)obj)._max == _max;
170 }
171
172 @Override
173 public String toString() {
174 return String.format("[%s]", _value);
175 }
176
177 /* *************************************************************************
178 * Static factory methods.
179 * ************************************************************************/
180
181 /**
182 * Create a new random {@code IntegerGene} with the given value and the
183 * given range. If the {@code value} isn't within the interval [min, max],
184 * no exception is thrown. In this case the method
185 * {@link IntegerGene#isValid()} returns {@code false}.
186 *
187 * @param value the value of the gene.
188 * @param min the minimal valid value of this gene (inclusively).
189 * @param max the maximal valid value of this gene (inclusively).
190 * @return a new {@code IntegerGene} with the given {@code value}
191 */
192 public static IntegerGene of(final int value, final int min, final int max) {
193 return new IntegerGene(value, min, max);
194 }
195
196 /**
197 * Create a new random {@code IntegerGene} with the given value and the
198 * given range. If the {@code value} isn't within the interval [min, max],
199 * no exception is thrown. In this case the method
200 * {@link IntegerGene#isValid()} returns {@code false}.
201 *
202 * @since 3.2
203 *
204 * @param value the value of the gene.
205 * @param range the integer range to use
206 * @return a new {@code IntegerGene} with the give {@code value}
207 * @throws NullPointerException if the given {@code range} is {@code null}.
208 */
209 public static IntegerGene of(final int value, final IntRange range) {
210 return IntegerGene.of(value, range.getMin(), range.getMax());
211 }
212
213 /**
214 * Create a new random {@code IntegerGene}. It is guaranteed that the value of
215 * the {@code IntegerGene} lies in the interval [min, max].
216 *
217 * @param min the minimal valid value of this gene (inclusively).
218 * @param max the maximal valid value of this gene (inclusively).
219 * @return a new random {@code IntegerGene}
220 */
221 public static IntegerGene of(final int min, final int max) {
222 return of(nextInt(getRandom(), min, max), min, max);
223 }
224
225 /**
226 * Create a new random {@code IntegerGene}. It is guaranteed that the value of
227 * the {@code IntegerGene} lies in the interval [min, max].
228 *
229 * @since 3.2
230 *
231 * @param range the integer range to use
232 * @return a new random {@code IntegerGene}
233 * @throws NullPointerException if the given {@code range} is {@code null}.
234 */
235 public static IntegerGene of(final IntRange range) {
236 return of(nextInt(getRandom(), range.getMin(), range.getMax()), range);
237 }
238
239 static ISeq<IntegerGene> seq(
240 final int min,
241 final int max,
242 final IntRange lengthRange
243 ) {
244 final Random r = getRandom();
245
246 return MSeq.<IntegerGene>ofLength(random.nextInt(lengthRange, r))
247 .fill(() -> new IntegerGene(nextInt(r, min, max), min, max))
248 .toISeq();
249 }
250
251 /**
252 * Returns a pseudo-random, uniformly distributed int value between min and
253 * max (min and max included).
254 *
255 * @param random the random engine to use for calculating the random int
256 * value
257 * @param min lower bound for generated integer
258 * @param max upper bound for generated integer
259 * @return a random integer greater than or equal to {@code min} and
260 * less than or equal to {@code max}
261 * @throws IllegalArgumentException if {@code min > max}
262 * @throws NullPointerException if the given {@code random}
263 * engine is {@code null}.
264 */
265 static int nextInt(
266 final Random random,
267 final int min, final int max
268 ) {
269 if (min > max) {
270 throw new IllegalArgumentException(format(
271 "Min >= max: %d >= %d", min, max
272 ));
273 }
274
275 final int diff = max - min + 1;
276 int result = 0;
277
278 if (diff <= 0) {
279 do {
280 result = random.nextInt();
281 } while (result < min || result > max);
282 } else {
283 result = random.nextInt(diff) + min;
284 }
285
286 return result;
287 }
288
289 }
|