Обновить
Удалены ненужные части, такие как for
, for
петля, и добавил splice()
. Эта функция будет мутировать исходный массив из-за splice()
. Использование splice()
в массиве последовательных упорядоченных номеров (даже после перетасовки) гарантирует набор уникальных чисел.
/**
* genRan(quantity, length)
*
* Need a given amount of unique random numbers.
*
* Given a number for how many random numbers are to be returned (@quantity) and a
* number that represents the range of consecutive numbers to extract the random
* numbers from (@length), this function will:
* - generate a full array of numbers with the length of @length
* - use shuffle() to shuffle the array to provide an array of randomly ordered numbers
* - splices the first @quantity numbers of the shuffled array
* - returns new array of unique random numbers
*
* @param {Number} quantity length of returned array.
* @param {Number} length length of an array of numbers.
*
* @return {Array} An array of unique random numbers.
*/
демонстрация
Подробная информация в Demo
var qty = 4
var len = 100;
function genRan(quantity, length) {
// Ensure that quantity is never greater than length
if (quantity > length) {
quantity = length;
}
// Create an array of consecutive numbers from 1 to N
var array = Array.from({
length: length
}, (value, key = 0) => key + 1);
// Run shuffle get the returned shuffled array
var shuffled = shuffle(array);
// return an array of N (quantity) random numbers
return shuffled.splice(0, quantity);
}
console.log(genRan(qty, len));
/* shuffle utility
|| Uses Fisher-Yates algorithm
*/
function shuffle(array) {
var i = 0;
var j = 0;
var temp = null;
for (i = array.length - 1; i > 0; i -= 1) {
j = Math.floor(Math.random() * (i + 1))
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}