IntegerGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.0.0).
003  * Copyright (c) 2007-2017 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.util.RandomRegistry.getRandom;
024 
025 import java.io.Serializable;
026 import java.util.Random;
027 
028 import io.jenetics.internal.math.random;
029 import io.jenetics.util.ISeq;
030 import io.jenetics.util.IntRange;
031 import io.jenetics.util.MSeq;
032 import io.jenetics.util.Mean;
033 
034 /**
035  * NumericGene implementation which holds a 32 bit integer number.
036  *
037  <p>This is a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html">
038  * value-based</a> class; use of identity-sensitive operations (including
039  * reference equality ({@code ==}), identity hash code, or synchronization) on
040  * instances of {@code IntegerGene} may have unpredictable results and should
041  * be avoided.
042  *
043  @see IntegerChromosome
044  *
045  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
046  @since 2.0
047  @version 4.0
048  */
049 public final class IntegerGene
050     extends AbstractNumericGene<Integer, IntegerGene>
051     implements
052         NumericGene<Integer, IntegerGene>,
053         Mean<IntegerGene>,
054         Comparable<IntegerGene>,
055         Serializable
056 {
057 
058     private static final long serialVersionUID = 1L;
059 
060     /**
061      * Create a new random {@code IntegerGene} with the given value and the
062      * given range. If the {@code value} isn't within the interval [min, max],
063      * no exception is thrown. In this case the method
064      {@link IntegerGene#isValid()} returns {@code false}.
065      *
066      @param value the value of the gene.
067      @param min the minimal valid value of this gene (inclusively).
068      @param max the maximal valid value of this gene (inclusively).
069      @throws NullPointerException if one of the arguments is {@code null}.
070      */
071     IntegerGene(final Integer value, final Integer min, final Integer max) {
072         super(value, min, max);
073     }
074 
075     @Override
076     public int compareTo(final IntegerGene other) {
077         return _value.compareTo(other._value);
078     }
079 
080     /**
081      * Create a new random {@code IntegerGene} with the given value and the
082      * given range. If the {@code value} isn't within the interval [min, max],
083      * no exception is thrown. In this case the method
084      {@link IntegerGene#isValid()} returns {@code false}.
085      *
086      @param value the value of the gene.
087      @param min the minimal valid value of this gene (inclusively).
088      @param max the maximal valid value of this gene (inclusively).
089      @return a new {@code IntegerGene} with the given {@code value}
090      */
091     public static IntegerGene of(final int value, final int min, final int max) {
092         return new IntegerGene(value, min, max);
093     }
094 
095     /**
096      * Create a new random {@code IntegerGene} with the given value and the
097      * given range. If the {@code value} isn't within the interval [min, max],
098      * no exception is thrown. In this case the method
099      {@link IntegerGene#isValid()} returns {@code false}.
100      *
101      @since 3.2
102      *
103      @param value the value of the gene.
104      @param range the integer range to use
105      @return a new {@code IntegerGene} with the give {@code value}
106      @throws NullPointerException if the given {@code range} is {@code null}.
107      */
108     public static IntegerGene of(final int value, final IntRange range) {
109         return new IntegerGene(value, range.getMin(), range.getMax());
110     }
111 
112     /**
113      * Create a new random {@code IntegerGene}. It is guaranteed that the value of
114      * the {@code IntegerGene} lies in the interval [min, max].
115      *
116      @param min the minimal valid value of this gene (inclusively).
117      @param max the maximal valid value of this gene (inclusively).
118      @return a new random {@code IntegerGene}
119      */
120     public static IntegerGene of(final int min, final int max) {
121         return of(nextInt(getRandom(), min, max), min, max);
122     }
123 
124     /**
125      * Create a new random {@code IntegerGene}. It is guaranteed that the value of
126      * the {@code IntegerGene} lies in the interval [min, max].
127      *
128      @since 3.2
129      *
130      @param range the integer range to use
131      @return a new random {@code IntegerGene}
132      @throws NullPointerException if the given {@code range} is {@code null}.
133      */
134     public static IntegerGene of(final IntRange range) {
135         return of(nextInt(getRandom(), range.getMin(), range.getMax()), range);
136     }
137 
138     static ISeq<IntegerGene> seq(
139         final Integer minimum,
140         final Integer maximum,
141         final IntRange lengthRange
142     ) {
143         final int min = minimum;
144         final int max = maximum;
145         final Random r = getRandom();
146 
147         return MSeq.<IntegerGene>ofLength(random.nextInt(lengthRange, r))
148             .fill(() -> new IntegerGene(nextInt(r, min, max), minimum, maximum))
149             .toISeq();
150     }
151 
152     @Override
153     public IntegerGene newInstance(final Number number) {
154         return new IntegerGene(number.intValue(), _min, _max);
155     }
156 
157     @Override
158     public IntegerGene newInstance() {
159         return new IntegerGene(
160             nextInt(getRandom(), _min, _max), _min, _max
161         );
162     }
163 
164     @Override
165     public IntegerGene mean(final IntegerGene that) {
166         return new IntegerGene(_value + (that._value - _value)/2, _min, _max);
167     }
168 
169     /**
170      * Returns a pseudo-random, uniformly distributed int value between min and
171      * max (min and max included).
172      *
173      @param random the random engine to use for calculating the random int
174      *        value
175      @param min lower bound for generated integer
176      @param max upper bound for generated integer
177      @return a random integer greater than or equal to {@code min} and
178      *         less than or equal to {@code max}
179      @throws IllegalArgumentException if {@code min > max}
180      @throws NullPointerException if the given {@code random}
181      *         engine is {@code null}.
182      */
183     static int nextInt(
184         final Random random,
185         final int min, final int max
186     ) {
187         if (min > max) {
188             throw new IllegalArgumentException(format(
189                 "Min >= max: %d >= %d", min, max
190             ));
191         }
192 
193         final int diff = max - min + 1;
194         int result = 0;
195 
196         if (diff <= 0) {
197             do {
198                 result = random.nextInt();
199             while (result < min || result > max);
200         else {
201             result = random.nextInt(diff+ min;
202         }
203 
204         return result;
205     }
206 
207 }