CharacterGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.2.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.util.Objects.requireNonNull;
023 
024 import java.io.Serializable;
025 import java.util.Objects;
026 import java.util.Random;
027 
028 import io.jenetics.internal.math.random;
029 import io.jenetics.util.CharSeq;
030 import io.jenetics.util.ISeq;
031 import io.jenetics.util.IntRange;
032 import io.jenetics.util.MSeq;
033 import io.jenetics.util.RandomRegistry;
034 
035 /**
036  * Character gene implementation.
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 CharacterGene} may have unpredictable results and should
042  * be avoided.
043  *
044  @see CharacterChromosome
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 1.0
051  @version 4.0
052  */
053 public final class CharacterGene
054     implements
055         Gene<Character, CharacterGene>,
056         Comparable<CharacterGene>,
057         Serializable
058 {
059     private static final long serialVersionUID = 2L;
060 
061     /**
062      * The default character set used by this gene.
063      */
064     public static final CharSeq DEFAULT_CHARACTERS = new CharSeq(
065         "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
066         " !\"$%&/()=?`{[]}\\+~*#';.:,-_<>|@^'"
067     );
068 
069     private final Character _character;
070     private final CharSeq _validCharacters;
071 
072     private CharacterGene(final CharSeq chars, final int index) {
073         _character = chars.get(index);
074         _validCharacters = chars;
075     }
076 
077     /**
078      * Create a new character gene from the given {@code character} and the
079      * given set of valid characters.
080      *
081      @param character the char this gene represents
082      @param validChars the set of valid characters.
083      @throws NullPointerException if one of the arguments is {@code null}.
084      */
085     CharacterGene(final Character character, final CharSeq validChars) {
086         _character = requireNonNull(character);
087         _validCharacters = requireNonNull(validChars);
088     }
089 
090     @Override
091     public boolean isValid() {
092         return _validCharacters.contains(_character);
093     }
094 
095     @Override
096     public Character getAllele() {
097         return _character;
098     }
099 
100     /**
101      * Return the {@code char} value of this character gene.
102      *
103      @return the {@code char} value.
104      */
105     public char charValue() {
106         return _character;
107     }
108 
109     /**
110      * Test, if the given character is valid.
111      *
112      @param character The character to test.
113      @return true if the character is valid, false otherwise.
114      */
115     public boolean isValidCharacter(final Character character) {
116         return _validCharacters.contains(character);
117     }
118 
119     /**
120      * Return a (unmodifiable) set of valid characters.
121      *
122      @return the {@link CharSeq} of valid characters.
123      */
124     public CharSeq getValidCharacters() {
125         return _validCharacters;
126     }
127 
128     /**
129      @see java.lang.Character#compareTo(java.lang.Character)
130      @param that The other gene to compare.
131      @return the value 0 if the argument Character is equal to this Character;
132      *         a value less than 0 if this Character is numerically less than
133      *         the Character argument; and a value greater than 0 if this
134      *         Character is numerically greater than the Character argument
135      *         (unsigned comparison). Note that this is strictly a numerical
136      *         comparison; it is not local-dependent.
137      */
138     @Override
139     public int compareTo(final CharacterGene that) {
140         return getAllele().compareTo(that.getAllele());
141     }
142 
143     @Override
144     public int hashCode() {
145         int hash = 17;
146         hash += 31*Objects.hashCode(_character37;
147         hash += 31*Objects.hashCode(_validCharacters37;
148         return hash;
149     }
150 
151     @Override
152     public boolean equals(final Object obj) {
153         return obj == this ||
154             obj instanceof CharacterGene &&
155             Objects.equals(((CharacterGene)obj)._character, _character&&
156             Objects.equals(((CharacterGene)obj)._validCharacters, _validCharacters);
157     }
158 
159     @Override
160     public String toString() {
161         return _character.toString();
162     }
163 
164 
165     /* *************************************************************************
166      *  Factory methods
167      * ************************************************************************/
168 
169     @Override
170     public CharacterGene newInstance() {
171         return of(_validCharacters);
172     }
173 
174     /**
175      * Create a new character gene from the given character. If the character
176      * is not within the {@link #getValidCharacters()}, an invalid gene will be
177      * created.
178      *
179      @param character the character value of the created gene.
180      @return a new character gene.
181      @throws NullPointerException if the given {@code character} is
182      *         {@code null}.
183      */
184     public CharacterGene newInstance(final Character character) {
185         return of(character, _validCharacters);
186     }
187 
188 
189     /* *************************************************************************
190      *  Static object creation methods
191      * ************************************************************************/
192 
193     /**
194      * Create a new CharacterGene with a randomly chosen character from the
195      * set of valid characters.
196      *
197      @param validCharacters the valid characters for this gene.
198      @return a new valid, <em>random</em> gene,
199      @throws NullPointerException if the {@code validCharacters} are
200      *         {@code null}.
201      */
202     public static CharacterGene of(final CharSeq validCharacters) {
203         return new CharacterGene(
204             validCharacters,
205             RandomRegistry.getRandom().nextInt(validCharacters.length())
206         );
207     }
208 
209     /**
210      * Create a new character gene from the given character. If the character
211      * is not within the {@link #DEFAULT_CHARACTERS}, an invalid gene will be
212      * created.
213      *
214      @param character the character value of the created gene.
215      @return a new character gene.
216      @throws NullPointerException if the given {@code character} is
217      *         {@code null}.
218      */
219     public static CharacterGene of(final Character character) {
220         return new CharacterGene(character, DEFAULT_CHARACTERS);
221     }
222 
223     /**
224      * Create a new random character gene, chosen from the
225      {@link #DEFAULT_CHARACTERS}.
226      *
227      @return a new random character gene.
228      */
229     public static CharacterGene of() {
230         return new CharacterGene(
231             DEFAULT_CHARACTERS,
232             RandomRegistry.getRandom().nextInt(DEFAULT_CHARACTERS.length())
233         );
234     }
235 
236     /**
237      * Create a new CharacterGene from the give character.
238      *
239      @param character The allele.
240      @param validCharacters the valid characters fo the new gene
241      @return a new {@code CharacterGene} with the given parameter
242      @throws NullPointerException if one of the arguments is {@code null}.
243      @throws IllegalArgumentException if the {@code validCharacters} are empty.
244      */
245     public static CharacterGene of(
246         final char character,
247         final CharSeq validCharacters
248     ) {
249         return new CharacterGene(character, validCharacters);
250     }
251 
252     static ISeq<CharacterGene> seq(
253         final CharSeq chars,
254         final IntRange lengthRange
255     ) {
256         final Random r = RandomRegistry.getRandom();
257 
258         return MSeq.<CharacterGene>ofLength(random.nextInt(lengthRange, r))
259             .fill(() -> new CharacterGene(chars, r.nextInt(chars.length())))
260             .toISeq();
261     }
262 
263 }