001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. 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 018package org.apache.commons.rng.sampling; 019 020import java.util.Collection; 021import java.util.List; 022import java.util.ArrayList; 023 024import org.apache.commons.rng.UniformRandomProvider; 025 026/** 027 * Sampling from a {@link Collection}. 028 * 029 * @param <T> Type of items in the collection. 030 * 031 * @since 1.0 032 */ 033public class CollectionSampler<T> { 034 /** Collection to be sampled from. */ 035 private final List<T> items; 036 /** RNG. */ 037 private final UniformRandomProvider rng; 038 039 /** 040 * Creates a sampler. 041 * 042 * @param rng Generator of uniformly distributed random numbers. 043 * @param collection Collection to be sampled. 044 * A (shallow) copy will be stored in the created instance. 045 * @throws IllegalArgumentException if {@code collection.size() <= 0}. 046 */ 047 public CollectionSampler(UniformRandomProvider rng, 048 Collection<T> collection) { 049 if (collection.size() <= 0) { 050 throw new IllegalArgumentException("Empty collection"); 051 } 052 053 this.rng = rng; 054 items = new ArrayList<T>(collection); 055 } 056 057 /** 058 * Picks one of the items in the given {@code collection}. 059 * 060 * <p> 061 * Sampling is without replacement; but if the source collection 062 * contains identical objects, the sample may include repeats. 063 * </p> 064 * <p> 065 * There is no guarantee that the concrete type of the returned 066 * collection is the same as the source collection. 067 * </p> 068 * 069 * @return a random sample. 070 */ 071 public T sample() { 072 return items.get(rng.nextInt(items.size())); 073 } 074}