Android Array Randomize getRandom(T... any)

Here you can find the source of getRandom(T... any)

Description

Gets random value get param any

License

Apache License

Parameter

Parameter Description
T a parameter
any a parameter

Declaration

public static <T> T getRandom(T... any) 

Method Source Code

//package com.java2s;
/**//from  w  ww.  java  2  s  .  c o  m
 * 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. randomList(List options)