/*
* Debellor
*
* Copyright (C) 2008-2009 by Marcin Wojnarski
*
* This program 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
* (at your option) any later version.
*
* This program 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 this program. If not, see http://www.gnu.org/licenses/.
*/
package org.debellor.core.util;
import java.util.Arrays;
import java.util.Random;
/**
* @author Marcin Wojnarski
*
*/
public class Permute {
/**
* Generates random combination of integers from [0,<code>range</code>),
* of length <code>length</code>, without repetitions.
* @param range Values will be picked randomly from [0,range) interval
* @param length Number of returned values. Must be <= <code>range</code>
* @param random Random number generator to be used
* @return Random combination of integers from [0,<code>range</code>),
* of length <code>length</code>, without repetitions.
*/
public static int[] indices(int range, int length, Random random) {
if((length > range) || (length < 0))
return null;
int[] a = new int[range];
for(int i = 0; i < range; i++)
a[i] = i;
// after this loop, a[0..(length-1)] will contain the desired combination
for(int i = 0; i < length; i++) {
int j = random.nextInt(range - i) + i;
if(i != j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
if(length == range)
return a;
return Arrays.copyOf(a, length);
}
public static int[] indices(int range, Random random) {
return indices(range, range, random);
}
public static int[] indices(int range) {
return indices(range, new Random());
}
}