LongGene.java
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.LongRange;
033 import io.jenetics.util.MSeq;
034 import io.jenetics.util.Mean;
035 
036 /**
037  * NumericGene implementation which holds a 64 bit integer number.
038  *
039  <p>This is a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html">
040  * value-based</a> class; use of identity-sensitive operations (including
041  * reference equality ({@code ==}), identity hash code, or synchronization) on
042  * instances of {@code LongGene} may have unpredictable results and should
043  * be avoided.
044  *
045  @see LongChromosome
046  *
047  * @implNote
048  * This class is immutable and thread-safe.
049  *
050  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
051  @since 1.6
052  @version 4.3
053  */
054 public final class LongGene
055     implements
056         NumericGene<Long, LongGene>,
057         Mean<LongGene>,
058         Comparable<LongGene>,
059         Serializable
060 {
061 
062     private static final long serialVersionUID = 2L;
063 
064     private final long _value;
065     private final long _min;
066     private final long _max;
067 
068     /**
069      * Create a new random {@code LongGene} with the given value and the
070      * given range. If the {@code value} isn't within the interval [min, max],
071      * no exception is thrown. In this case the method
072      {@link LongGene#isValid()} returns {@code false}.
073      *
074      @param value the value of the gene.
075      @param min the minimal valid value of this gene (inclusively).
076      @param max the maximal valid value of this gene (inclusively).
077      */
078     private LongGene(final long value, final long min, final long max) {
079         _value = value;
080         _min = min;
081         _max = max;
082     }
083 
084     @Override
085     public Long getAllele() {
086         return _value;
087     }
088 
089     @Override
090     public Long getMin() {
091         return _min;
092     }
093 
094     @Override
095     public Long getMax() {
096         return _max;
097     }
098 
099     @Override
100     public byte byteValue() {
101         return (byte)_value;
102     }
103 
104     @Override
105     public short shortValue() {
106         return (short)_value;
107     }
108 
109     @Override
110     public int intValue() {
111         return (int)_value;
112     }
113 
114     @Override
115     public long longValue() {
116         return _value;
117     }
118 
119     @Override
120     public float floatValue() {
121         return (float)_value;
122     }
123 
124     @Override
125     public double doubleValue() {
126         return _value;
127     }
128 
129     @Override
130     public boolean isValid() {
131         return _value >= _min && _value <= _max;
132     }
133 
134     @Override
135     public int compareTo(final LongGene other) {
136         return Long.compare(_value, other._value);
137     }
138 
139     @Override
140     public LongGene newInstance(final Long number) {
141         return LongGene.of(number, _min, _max);
142     }
143 
144     @Override
145     public LongGene newInstance(final Number number) {
146         return LongGene.of(number.longValue(), _min, _max);
147     }
148 
149     @Override
150     public LongGene newInstance() {
151         return LongGene.of(nextLong(getRandom(), _min, _max), _min, _max);
152     }
153 
154     @Override
155     public LongGene mean(final LongGene that) {
156         return LongGene.of(_value + (that._value - _value)/2, _min, _max);
157     }
158 
159     @Override
160     public int hashCode() {
161         return hash(_value, hash(_min, hash(_max, hash(getClass()))));
162     }
163 
164     @Override
165     public boolean equals(final Object obj) {
166         return obj == this ||
167             obj instanceof LongGene &&
168             ((LongGene)obj)._value == _value &&
169             ((LongGene)obj)._min == _min &&
170             ((LongGene)obj)._max == _max;
171     }
172 
173     @Override
174     public String toString() {
175         return String.format("[%s]", _value);
176     }
177 
178     /* *************************************************************************
179      * Static factory methods.
180      * ************************************************************************/
181 
182     /**
183      * Create a new random {@code LongGene} with the given value and the
184      * given range. If the {@code value} isn't within the interval [min, max],
185      * no exception is thrown. In this case the method
186      {@link LongGene#isValid()} returns {@code false}.
187      *
188      @param value the value of the gene.
189      @param min the minimal valid value of this gene (inclusively).
190      @param max the maximal valid value of this gene (inclusively).
191      @return a new {@code LongGene} with the given parameters.
192      */
193     public static LongGene of(final long value, final long min, final long max) {
194         return new LongGene(value, min, max);
195     }
196 
197     /**
198      * Create a new random {@code LongGene} with the given value and the
199      * given range. If the {@code value} isn't within the interval [min, max],
200      * no exception is thrown. In this case the method
201      {@link LongGene#isValid()} returns {@code false}.
202      *
203      @since 3.2
204      *
205      @param value the value of the gene.
206      @param range the long range to use
207      @return a new random {@code LongGene}
208      @throws NullPointerException if the given {@code range} is {@code null}.
209      */
210     public static LongGene of(final long value, final LongRange range) {
211         return LongGene.of(value, range.getMin(), range.getMax());
212     }
213 
214     /**
215      * Create a new random {@code LongGene}. It is guaranteed that the value of
216      * the {@code LongGene} lies in the interval [min, max].
217      *
218      @param min the minimal valid value of this gene (inclusively).
219      @param max the maximal valid value of this gene (inclusively).
220      @return a new {@code LongGene} with the given parameters.
221      */
222     public static LongGene of(final long min, final long max) {
223         return of(nextLong(getRandom(), min, max), min, max);
224     }
225 
226     /**
227      * Create a new random {@code LongGene}. It is guaranteed that the value of
228      * the {@code LongGene} lies in the interval [min, max].
229      *
230      @since 3.2
231      *
232      @param range the long range to use
233      @return a new random {@code LongGene}
234      @throws NullPointerException if the given {@code range} is {@code null}.
235      */
236     public static LongGene of(final LongRange range) {
237         return of(nextLong(getRandom(), range.getMin(), range.getMax()), range);
238     }
239 
240     static ISeq<LongGene> seq(
241         final long min,
242         final long max,
243         final IntRange lengthRange
244     ) {
245         final Random r = getRandom();
246 
247         return MSeq.<LongGene>ofLength(random.nextInt(lengthRange, r))
248             .fill(() -> LongGene.of(nextLong(r, min, max), min, max))
249             .toISeq();
250     }
251 
252     /**
253      * Returns a pseudo-random, uniformly distributed int value between min
254      * and max (min and max included).
255      *
256      @param random the random engine to use for calculating the random
257      *        long value
258      @param min lower bound for generated long integer
259      @param max upper bound for generated long integer
260      @return a random long integer greater than or equal to {@code min}
261      *         and less than or equal to {@code max}
262      @throws IllegalArgumentException if {@code min > max}
263      @throws NullPointerException if the given {@code random}
264      *         engine is {@code null}.
265      */
266     static long nextLong(
267         final Random random,
268         final long min, final long max
269     ) {
270         if (min > max) {
271             throw new IllegalArgumentException(format(
272                 "min >= max: %d >= %d.", min, max
273             ));
274         }
275 
276         final long diff = (max - min1;
277         long result = 0;
278 
279         if (diff <= 0) {
280             do {
281                 result = random.nextLong();
282             while (result < min || result > max);
283         else if (diff < Integer.MAX_VALUE) {
284             result = random.nextInt((int)diff+ min;
285         else {
286             result = nextLong(random, diff+ min;
287         }
288 
289         return result;
290     }
291 
292     /**
293      * Returns a pseudo-random, uniformly distributed int value between 0
294      * (inclusive) and the specified value (exclusive), drawn from the given
295      * random number generator's sequence.
296      *
297      @param random the random engine used for creating the random number.
298      @param n the bound on the random number to be returned. Must be
299      *        positive.
300      @return the next pseudo-random, uniformly distributed int value
301      *         between 0 (inclusive) and n (exclusive) from the given random
302      *         number generator's sequence
303      @throws IllegalArgumentException if n is smaller than 1.
304      @throws NullPointerException if the given {@code random}
305      *         engine is {@code null}.
306      */
307     static long nextLong(final Random random, final long n) {
308         if (n <= 0) {
309             throw new IllegalArgumentException(format(
310                 "n is smaller than one: %d", n
311             ));
312         }
313 
314         long bits;
315         long result;
316         do {
317             bits = random.nextLong() 0x7fffffffffffffffL;
318             result = bits%n;
319         while (bits - result + (n - 10);
320 
321         return result;
322     }
323 
324 }