Here you can find the source of getRandomNumbers(int range, int count, Random rnd)
public static ArrayList<Integer> getRandomNumbers(int range, int count, Random rnd)
//package com.java2s; /* /*w w w . ja va 2 s.c om*/ * Copyright 2008-2013, ETH Z?rich, Samuel Welten, Michael Kuhn, Tobias Langner, * Sandro Affentranger, Lukas Bossard, Michael Grob, Rahul Jain, * Dominic Langenegger, Sonia Mayor Alonso, Roger Odermatt, Tobias Schlueter, * Yannick Stucki, Sebastian Wendland, Samuel Zehnder, Samuel Zihlmann, * Samuel Zweifel * * This file is part of Jukefox. * * Jukefox is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or any later version. Jukefox is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * Jukefox. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class Main { public static ArrayList<Integer> getRandomNumbers(int range, int count, Random rnd) { // long t1 = System.currentTimeMillis(); if (count > range) { return null; } if (count < 0 || range < 0) { return null; } ArrayList<Integer> indices = new ArrayList<Integer>(); if (count < range / 2) { HashMap<Integer, Integer> used = new HashMap<Integer, Integer>(); int n = range; while (indices.size() < count) { Integer r = Integer.valueOf(rnd.nextInt(n)); if (used.containsKey(r)) { indices.add(used.get(r)); } else { indices.add(r); } addToUsed(used, r, n - 1); n--; } } else { ArrayList<Integer> unused = new ArrayList<Integer>(range); for (int i = 0; i < range; i++) { // Log.v(TAG, "TT" + i + " " + (System.currentTimeMillis() - t1)); unused.add(i); } int u = 0; while (indices.size() < count) { // Log.v(TAG, "TD" + u + " " + (System.currentTimeMillis() - t1)); Integer r = unused.remove(rnd.nextInt(unused.size())); indices.add(r); u++; } } return indices; } private static void addToUsed(HashMap<Integer, Integer> used, Integer key, Integer value) { if (used.containsKey(value)) { value = used.get(value); addToUsed(used, key, value); } used.put(key, value); } }