IndexStream.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-1.6.0).
003  * Copyright (c) 2007-2014 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@gmx.at)
019  */
020 package org.jenetics.util;
021 
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024 
025 import java.util.Random;
026 
027 import org.jenetics.internal.math.probability;
028 
029 /**
030  * Interface which delivers a stream of (positive) indexes ({@code int}s)s. The
031  * stream ends if {@link #next()} returns {@code -1}. Here some usage examples:
032  *
033  * [code]
034  * final IndexStream stream = ...;
035  * for (int index = stream.next(); index != -1; index = stream.next()) {
036  *     System.out.println(index);
037  * }
038  * [/code]
039  * [code]
040  * final IndexStream stream = ...;
041  * int index = 0;
042  * while ((index = stream.next()) != -1) {
043  *     System.out.println(index);
044  * }
045  * [/code]
046  *
047  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
048  @since 1.0
049  @version 1.1 &mdash; <em>$Date: 2014-02-15 $</em>
050  */
051 public abstract class IndexStream {
052 
053     protected IndexStream() {
054     }
055 
056     /**
057      * Return the next (positive inclusive zero) index, or -1 if the stream has
058      * reached its end.
059      *
060      @return the next index, or -1 if the stream has reached its end.
061      */
062     public abstract int next();
063 
064     /**
065      * Applies a {@code function} to all elements of this stream.
066      *
067      @param function the function to apply to the elements.
068      @throws NullPointerException if the given {@code function} is
069      *         {@code null}.
070      */
071     <R> void forEach(final Function<? super Integer, ? extends R> function) {
072         requireNonNull(function, "Function");
073         for (int i = next(); i != -1; i = next()) {
074             function.apply(i);
075         }
076     }
077 
078     /**
079      * Create a new random IndexIterator.
080      @param n the maximal value (exclusively) the created index stream will
081      *         return.
082      @param probability the index selection probability.
083      @throws IllegalArgumentException if {@code n == Integer.MAX_VALUE} or
084      *         {@code n <= 0} or the given {@code probability} is not valid.
085      */
086     public static IndexStream Random(final int n, final double probability) {
087         return Random(n, probability, RandomRegistry.getRandom());
088     }
089 
090     /**
091      * Create a new random IndexIterator. The elements returned by this stream
092      * are strictly increasing.
093      *
094      @param n the maximal value (exclusively) the created index stream will
095      *        return.
096      @param p the index selection probability.
097      @param random the random engine used for creating the random indexes.
098      @throws IllegalArgumentException if {@code n == Integer.MAX_VALUE} or
099      *         {@code n <= 0} or the given {@code probability} is not valid.
100      @throws NullPointerException if the given {@code random} engine is
101      *         {@code null}.
102      */
103     public static IndexStream Random(
104         final int n,
105         final double p,
106         final Random random
107     ) {
108         if (n == Integer.MAX_VALUE) {
109             throw new IllegalArgumentException(format(
110                 "n must be smaller than Integer.MAX_VALUE."
111             ));
112         }
113         if (n <= 0) {
114             throw new IllegalArgumentException(format(
115                 "n must be greater than zero: %d", n
116             ));
117         }
118 
119         IndexStream stream = new RandomIndexStream(n, p, random);
120         if (Double.compare(p, 0.0== 0) {
121             stream = new RandomIndexStreamP0();
122         else if (Double.compare(p, 1.0== 0) {
123             stream = new RandomIndexStreamP1(n);
124         }
125         return stream;
126     }
127 
128 }
129 
130 /**
131  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
132  @since 1.4
133  @version 1.5 &mdash; <em>$Date: 2014-02-15 $</em>
134  */
135 final class RandomIndexStream extends IndexStream {
136     private final int _n;
137     private final int _p;
138     private final Random _random;
139 
140     private int _pos = -1;
141 
142     RandomIndexStream(final int n, final double p, final Random random) {
143         _n = n;
144         _p = probability.toInt(p);
145         _random = requireNonNull(random, "Random object must not be null.");
146     }
147 
148     @Override
149     public final int next() {
150         while (_pos < _n && _random.nextInt() >= _p) {
151             ++_pos;
152         }
153         ++_pos;
154 
155         return _pos < _n ? _pos : -1;
156     }
157 }
158 
159 /**
160  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
161  @since 1.5
162  @version 1.5 &mdash; <em>$Date: 2014-02-15 $</em>
163  */
164 final class RandomIndexStreamP0 extends IndexStream {
165     @Override public int next() {
166         return -1;
167     }
168 }
169 
170 /**
171  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
172  @since 1.5
173  @version 1.5 &mdash; <em>$Date: 2014-02-15 $</em>
174  */
175 final class RandomIndexStreamP1 extends IndexStream {
176     private final int _n;
177     private int _pos = -1;
178 
179     RandomIndexStreamP1(final int n) {
180         _n = n;
181     }
182 
183     @Override public int next() {
184         ++_pos;
185         return _pos < _n ? _pos : -1;
186     }
187 }