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