Choose random numbers from 0 to n-1 - Android java.util

Android examples for java.util:Random

Description

Choose random numbers from 0 to n-1

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    public static final Random RANDOM = new Random();

    /**/*from   ww w.  ja  v a 2s.  c om*/
     * Choose random numbers from 0 to n-1
     *
     * @param n       the choice limit.
     * @param results the array to put the choices. Infinite loop if length > n.
     */
    public static void choose(int n, int[] results) {
        int k = results.length;
        for (int i = 0; i < k; i++) {
            boolean done = false;
            while (!done) {
                results[i] = RANDOM.nextInt(n);
                done = true;
                for (int j = 0; j < i; j++) {
                    if (results[j] == results[i]) {
                        done = false;
                    }
                }
            }
        }
    }
}

Related Tutorials