1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package org.apache.commons.rng.sampling.distribution; 19 20 import org.apache.commons.rng.UniformRandomProvider; 21 22 /** 23 * Discrete uniform distribution sampler. 24 * 25 * @since 1.0 26 */ 27 public class DiscreteUniformSampler 28 extends SamplerBase 29 implements DiscreteSampler { 30 /** Lower bound. */ 31 private final int lower; 32 /** Upper bound. */ 33 private final int upper; 34 /** Underlying source of randomness. */ 35 private final UniformRandomProvider rng; 36 37 /** 38 * @param rng Generator of uniformly distributed random numbers. 39 * @param lower Lower bound (inclusive) of the distribution. 40 * @param upper Upper bound (inclusive) of the distribution. 41 * @throws IllegalArgumentException if {@code lower > upper}. 42 */ 43 public DiscreteUniformSampler(UniformRandomProvider rng, 44 int lower, 45 int upper) { 46 super(null); 47 this.rng = rng; 48 if (lower > upper) { 49 throw new IllegalArgumentException(lower + " > " + upper); 50 } 51 52 this.lower = lower; 53 this.upper = upper; 54 } 55 56 /** {@inheritDoc} */ 57 @Override 58 public int sample() { 59 final int max = (upper - lower) + 1; 60 if (max <= 0) { 61 // The range is too wide to fit in a positive int (larger 62 // than 2^31); as it covers more than half the integer range, 63 // we use a simple rejection method. 64 while (true) { 65 final int r = rng.nextInt(); 66 if (r >= lower && 67 r <= upper) { 68 return r; 69 } 70 } 71 } else { 72 // We can shift the range and directly generate a positive int. 73 return lower + rng.nextInt(max); 74 } 75 } 76 77 /** {@inheritDoc} */ 78 @Override 79 public String toString() { 80 return "Uniform deviate [" + rng.toString() + "]"; 81 } 82 }