001/* 002 * Java Genetic Algorithm Library (jenetics-7.2.0). 003 * Copyright (c) 2007-2023 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.ext.grammar; 021 022import static java.util.Objects.requireNonNull; 023 024import java.util.random.RandomGenerator; 025 026import io.jenetics.ext.grammar.Cfg.Rule; 027 028/** 029 * Functional interface for selecting a {@link Cfg.Symbol} by its index within a 030 * rule. It is an abstraction of the <em>codon</em> values used for selecting 031 * the alternatives from a rule during the sentence generation. 032 * 033 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> 034 * @since 7.1 035 * @version 7.1 036 */ 037@FunctionalInterface 038public interface SymbolIndex { 039 040 /** 041 * Selects an index with the given upper {@code bound}, exclusively. 042 * 043 * @param rule the rule which requested the index 044 * @param bound the upper bound of the symbol index, exclusively 045 * @return the next symbol index 046 * @throws IllegalArgumentException if the given {@code bound} is smaller 047 * than one 048 */ 049 int next(final Rule<?> rule, final int bound); 050 051 /** 052 * Create a new symbol-index object from the given random generator. This 053 * can be used for generating random sentences of derivation-trees. 054 * 055 * @param random the random generator used for generating the sentences 056 * @return a new symbol-index object from the given random generator 057 * @throws NullPointerException if the given {@code random} generator is 058 * {@code null} 059 */ 060 static SymbolIndex of(final RandomGenerator random) { 061 requireNonNull(random); 062 return (rule, bound) -> random.nextInt(bound); 063 } 064 065}