Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (c) 2009-2015, b3log.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Gets a list of integers(size specified by the given size) between the
     * specified start(inclusion) and end(inclusion) randomly.
     *
     * @param start the specified start
     * @param end the specified end
     * @param size the given size
     * @return a list of integers
     */
    public static List<Integer> getRandomIntegers(final int start, final int end, final int size) {
        if (size > (end - start + 1)) {
            throw new IllegalArgumentException("The specified size more then (end - start + 1)!");
        }

        final List<Integer> integers = genIntegers(start, end);
        final List<Integer> ret = new ArrayList<Integer>();

        int remainsSize;
        int index;

        while (ret.size() < size) {
            remainsSize = integers.size();
            index = (int) (Math.random() * (remainsSize - 1));
            final Integer i = integers.get(index);

            ret.add(i);
            integers.remove(i);
        }

        return ret;
    }

    /**
     * Generates a list of integers from the specified start(inclusion) to the
     * specified end(inclusion).
     *
     * @param start the specified start
     * @param end the specified end
     * @return a list of integers
     */
    public static List<Integer> genIntegers(final int start, final int end) {
        final List<Integer> ret = new ArrayList<Integer>();

        for (int i = 0; i <= end; i++) {
            ret.add(i + start);
        }

        return ret;
    }
}