LongGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.4.0).
003  * Copyright (c) 2007-2019 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     /**
100      * Return the range of {@code this} gene.
101      *
102      @since 4.4
103      *
104      @return the range of {@code this} gene
105      */
106     public LongRange range() {
107         return LongRange.of(_min, _max);
108     }
109 
110     @Override
111     public byte byteValue() {
112         return (byte)_value;
113     }
114 
115     @Override
116     public short shortValue() {
117         return (short)_value;
118     }
119 
120     @Override
121     public int intValue() {
122         return (int)_value;
123     }
124 
125     @Override
126     public long longValue() {
127         return _value;
128     }
129 
130     @Override
131     public float floatValue() {
132         return (float)_value;
133     }
134 
135     @Override
136     public double doubleValue() {
137         return _value;
138     }
139 
140     @Override
141     public boolean isValid() {
142         return _value >= _min && _value <= _max;
143     }
144 
145     @Override
146     public int compareTo(final LongGene other) {
147         return Long.compare(_value, other._value);
148     }
149 
150     @Override
151     public LongGene newInstance(final Long number) {
152         return LongGene.of(number, _min, _max);
153     }
154 
155     @Override
156     public LongGene newInstance(final Number number) {
157         return LongGene.of(number.longValue(), _min, _max);
158     }
159 
160     @Override
161     public LongGene newInstance() {
162         return LongGene.of(nextLong(getRandom(), _min, _max), _min, _max);
163     }
164 
165     @Override
166     public LongGene mean(final LongGene that) {
167         return LongGene.of(_value + (that._value - _value)/2, _min, _max);
168     }
169 
170     @Override
171     public int hashCode() {
172         return hash(_value, hash(_min, hash(_max, hash(getClass()))));
173     }
174 
175     @Override
176     public boolean equals(final Object obj) {
177         return obj == this ||
178             obj instanceof LongGene &&
179             ((LongGene)obj)._value == _value &&
180             ((LongGene)obj)._min == _min &&
181             ((LongGene)obj)._max == _max;
182     }
183 
184     @Override
185     public String toString() {
186         return String.format("[%s]", _value);
187     }
188 
189     /* *************************************************************************
190      * Static factory methods.
191      * ************************************************************************/
192 
193     /**
194      * Create a new random {@code LongGene} with the given value and the
195      * given range. If the {@code value} isn't within the interval [min, max],
196      * no exception is thrown. In this case the method
197      {@link LongGene#isValid()} returns {@code false}.
198      *
199      @param value the value of the gene.
200      @param min the minimal valid value of this gene (inclusively).
201      @param max the maximal valid value of this gene (inclusively).
202      @return a new {@code LongGene} with the given parameters.
203      */
204     public static LongGene of(final long value, final long min, final long max) {
205         return new LongGene(value, min, max);
206     }
207 
208     /**
209      * Create a new random {@code LongGene} with the given value and the
210      * given range. If the {@code value} isn't within the interval [min, max],
211      * no exception is thrown. In this case the method
212      {@link LongGene#isValid()} returns {@code false}.
213      *
214      @since 3.2
215      *
216      @param value the value of the gene.
217      @param range the long range to use
218      @return a new random {@code LongGene}
219      @throws NullPointerException if the given {@code range} is {@code null}.
220      */
221     public static LongGene of(final long value, final LongRange range) {
222         return LongGene.of(value, range.getMin(), range.getMax());
223     }
224 
225     /**
226      * Create a new random {@code LongGene}. It is guaranteed that the value of
227      * the {@code LongGene} lies in the interval [min, max].
228      *
229      @param min the minimal valid value of this gene (inclusively).
230      @param max the maximal valid value of this gene (inclusively).
231      @return a new {@code LongGene} with the given parameters.
232      */
233     public static LongGene of(final long min, final long max) {
234         return of(nextLong(getRandom(), min, max), min, max);
235     }
236 
237     /**
238      * Create a new random {@code LongGene}. It is guaranteed that the value of
239      * the {@code LongGene} lies in the interval [min, max].
240      *
241      @since 3.2
242      *
243      @param range the long range to use
244      @return a new random {@code LongGene}
245      @throws NullPointerException if the given {@code range} is {@code null}.
246      */
247     public static LongGene of(final LongRange range) {
248         return of(nextLong(getRandom(), range.getMin(), range.getMax()), range);
249     }
250 
251     static ISeq<LongGene> seq(
252         final long min,
253         final long max,
254         final IntRange lengthRange
255     ) {
256         final Random r = getRandom();
257 
258         return MSeq.<LongGene>ofLength(random.nextInt(lengthRange, r))
259             .fill(() -> LongGene.of(nextLong(r, min, max), min, max))
260             .toISeq();
261     }
262 
263     /**
264      * Returns a pseudo-random, uniformly distributed int value between min
265      * and max (min and max included).
266      *
267      @param random the random engine to use for calculating the random
268      *        long value
269      @param min lower bound for generated long integer
270      @param max upper bound for generated long integer
271      @return a random long integer greater than or equal to {@code min}
272      *         and less than or equal to {@code max}
273      @throws IllegalArgumentException if {@code min > max}
274      @throws NullPointerException if the given {@code random}
275      *         engine is {@code null}.
276      */
277     static long nextLong(
278         final Random random,
279         final long min, final long max
280     ) {
281         if (min > max) {
282             throw new IllegalArgumentException(format(
283                 "min >= max: %d >= %d.", min, max
284             ));
285         }
286 
287         final long diff = (max - min1;
288         long result = 0;
289 
290         if (diff <= 0) {
291             do {
292                 result = random.nextLong();
293             while (result < min || result > max);
294         else if (diff < Integer.MAX_VALUE) {
295             result = random.nextInt((int)diff+ min;
296         else {
297             result = nextLong(random, diff+ min;
298         }
299 
300         return result;
301     }
302 
303     /**
304      * Returns a pseudo-random, uniformly distributed int value between 0
305      * (inclusive) and the specified value (exclusive), drawn from the given
306      * random number generator's sequence.
307      *
308      @param random the random engine used for creating the random number.
309      @param n the bound on the random number to be returned. Must be
310      *        positive.
311      @return the next pseudo-random, uniformly distributed int value
312      *         between 0 (inclusive) and n (exclusive) from the given random
313      *         number generator's sequence
314      @throws IllegalArgumentException if n is smaller than 1.
315      @throws NullPointerException if the given {@code random}
316      *         engine is {@code null}.
317      */
318     static long nextLong(final Random random, final long n) {
319         if (n <= 0) {
320             throw new IllegalArgumentException(format(
321                 "n is smaller than one: %d", n
322             ));
323         }
324 
325         long bits;
326         long result;
327         do {
328             bits = random.nextLong() 0x7fffffffffffffffL;
329             result = bits%n;
330         while (bits - result + (n - 10);
331 
332         return result;
333     }
334 
335 }