View Javadoc
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;
19  
20  import java.util.Collection;
21  import java.util.List;
22  import java.util.ArrayList;
23  
24  import org.apache.commons.rng.UniformRandomProvider;
25  
26  /**
27   * Sampling from a {@link Collection}.
28   *
29   * @param <T> Type of items in the collection.
30   *
31   * @since 1.0
32   */
33  public class CollectionSampler<T> {
34      /** Collection to be sampled from. */
35      private final List<T> items;
36      /** RNG. */
37      private final UniformRandomProvider rng;
38  
39      /**
40       * Creates a sampler.
41       *
42       * @param rng Generator of uniformly distributed random numbers.
43       * @param collection Collection to be sampled.
44       * A (shallow) copy will be stored in the created instance.
45       * @throws IllegalArgumentException if {@code collection} is empty.
46       */
47      public CollectionSampler(UniformRandomProvider rng,
48                               Collection<T> collection) {
49          if (collection.isEmpty()) {
50              throw new IllegalArgumentException("Empty collection");
51          }
52  
53          this.rng = rng;
54          items = new ArrayList<T>(collection);
55      }
56  
57      /**
58       * Picks one of the items from the
59       * {@link #CollectionSampler(UniformRandomProvider,Collection)
60       * collection passed to the constructor}.
61       *
62       * @return a random sample.
63       */
64      public T sample() {
65          return items.get(rng.nextInt(items.size()));
66      }
67  }