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