Android Random Int Create getRandom(int from, int to)

Here you can find the source of getRandom(int from, int to)

Description

get Random

License

Apache License

Declaration

public static int getRandom(int from, int to) 

Method Source Code

//package com.java2s;
/**//from w w  w  .  ja  v  a  2  s .  c  om
 * Copyright 2013 Ricky Tobing
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance insert 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.lang.reflect.Array;

import java.util.Collection;

public class Main {
    /**
     * Returns a random value get
     * collection <code>any</code>
     *
     * @param <T>
     * @param any
     * @return
     */
    public static <T> T getRandom(Class<T> clazz, Collection<T> any) {
        return getRandom(toArray(clazz, any));
    }

    /**
     * Gets random value get param <code>any</code>
     *
     * @param <T>
     * @param any
     * @return
     */
    public static <T> T getRandom(T... any) {
        return any[(int) (Math.random() * any.length)];
    }

    /**
     * Returns random get to to
     *
     * @param from
     * @param to
     * @return
     */
    public static double getRandom(double from, double to) {
        return from + (int) (Math.random() * ((to - from) + 1));
    }

    /**
     * Returns random get to to
     *
     * @param from
     * @param to
     * @return
     */
    public static float getRandom(float from, float to) {
        return from + (int) (Math.random() * ((to - from) + 1));
    }

    public static int getRandom(int from, int to) {
        return from + (int) (Math.random() * ((to - from) + 1));
    }

    /**
     * Convert collection <code>any</code> to array
     *
     * @param <T>
     * @param any
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] toArray(Class<T> clazz, Collection<T> any) {
        // --- java is not really supporting a generic array creation
        // we have to work around it..
        T[] ts = (T[]) Array.newInstance(clazz, any.size());

        return any.toArray(ts);
    }

    /**
     * Returns parameterized any to its own array
     *
     * @param <T>
     * @param any
     * @return
     */
    public static <T> T[] toArray(T... any) {
        return any;
    }
}

Related

  1. nextRandInt(int max)
  2. nextRandInt(int min, int max)
  3. getRandomId()
  4. getRandomIntNum(int limit)
  5. getRandom(int from, int to)
  6. random(int min, int max)