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 * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p>
30 *
31 * @param <T> Type of items in the collection.
32 *
33 * @since 1.0
34 */
35 public class CollectionSampler<T> implements SharedStateObjectSampler<T> {
36 /** Collection to be sampled from. */
37 private final List<T> items;
38 /** RNG. */
39 private final UniformRandomProvider rng;
40
41 /**
42 * Creates a sampler.
43 *
44 * @param rng Generator of uniformly distributed random numbers.
45 * @param collection Collection to be sampled.
46 * A (shallow) copy will be stored in the created instance.
47 * @throws IllegalArgumentException if {@code collection} is empty.
48 */
49 public CollectionSampler(UniformRandomProvider rng,
50 Collection<T> collection) {
51 if (collection.isEmpty()) {
52 throw new IllegalArgumentException("Empty collection");
53 }
54
55 this.rng = rng;
56 items = new ArrayList<>(collection);
57 }
58
59 /**
60 * @param rng Generator of uniformly distributed random numbers.
61 * @param source Source to copy.
62 */
63 private CollectionSampler(UniformRandomProvider rng,
64 CollectionSampler<T> source) {
65 this.rng = rng;
66 items = source.items;
67 }
68
69 /**
70 * Picks one of the items from the
71 * {@link #CollectionSampler(UniformRandomProvider,Collection)
72 * collection passed to the constructor}.
73 *
74 * @return a random sample.
75 */
76 @Override
77 public T sample() {
78 return items.get(rng.nextInt(items.size()));
79 }
80
81 /**
82 * {@inheritDoc}
83 *
84 * @since 1.3
85 */
86 @Override
87 public CollectionSampler<T> withUniformRandomProvider(UniformRandomProvider rng) {
88 return new CollectionSampler<>(rng, this);
89 }
90 }