Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

import java.util.Random;

public class Main {
    /**
     * Samples without replacement from a collection.
     *
     * @param c
     *          The collection to be sampled from
     * @param n
     *          The number of samples to take
     * @return a new collection with the sample
     */
    public static <E> Collection<E> sampleWithoutReplacement(Collection<E> c, int n) {
        return sampleWithoutReplacement(c, n, new Random());
    }

    /**
     * Samples without replacement from a collection, using your own
     * {@link Random} number generator.
     *
     * @param c
     *          The collection to be sampled from
     * @param n
     *          The number of samples to take
     * @param r
     *          the random number generator
     * @return a new collection with the sample
     */
    public static <E> Collection<E> sampleWithoutReplacement(Collection<E> c, int n, Random r) {
        if (n < 0)
            throw new IllegalArgumentException("n < 0: " + n);
        if (n > c.size())
            throw new IllegalArgumentException("n > size of collection: " + n + ", " + c.size());
        List<E> copy = new ArrayList<E>(c.size());
        copy.addAll(c);
        Collection<E> result = new ArrayList<E>(n);
        for (int k = 0; k < n; k++) {
            double d = r.nextDouble();
            int x = (int) (d * copy.size());
            result.add(copy.remove(x));
        }
        return result;
    }

    /**
     * Add all the items from an iterable to a collection.
     *
     * @param <T>
     *          The type of items in the iterable and the collection
     * @param collection
     *          The collection to which the items should be added.
     * @param items
     *          The items to add to the collection.
     */
    public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {
        for (T item : items) {
            collection.add(item);
        }
    }
}