我需要将从low到high的数字随机放置在一个数组中。
例如: low = 10,high = 15 --像[ 12, 13, 10, 14, 11]这样的结果是好的。
这是一个简单的算法:从低到高迭代,然后尝试填充数组上的空槽。
const low = 1000
const high = 1010
const diff = high - low
const arr = new Array(diff)
for (var i = low; i < high; i++) {
let success = false
while(!success) {
const index = Math.floor(Math.random() * diff)
if (arr[index] === undefined) {
arr[index] = i
success = true
}
console.log(`${index} was ${success ? 'available' : 'taken'}`)
}
}
console.log(arr)
问题是:在大多数元素都被填充的情况下,很难在数组中找到一个空槽。
我的问题是:是否有一种算法会不断地生成唯一的新数字,直到所有的数字都被消耗掉?
另一种思考它的方法是一种对数组进行最高效、最快速处理的算法。
发布于 2018-07-05 11:10:29
与其生成“随机”数字,不如生成一个数字列表,并使用类似于费舍-耶茨洗牌的方法“随机地”对其进行洗牌。
function getRandomArray(min, max) {
return shuffle([...Array(max - min).keys()].map(i => i + min));
}
function shuffle(array) {
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
var randomArr = getRandomArray(10, 15);
console.log(randomArr);发布于 2018-07-05 12:04:10
费舍-耶茨洗牌的另一个实现:
const low = 1000
const high = 1010
const delta = high - low
const arr = [...new Array(delta)]
arr.forEach((value, index, arr) => arr[index] = index + low)
const result = []
while (arr.length > 0) {
const index = Math.floor(Math.random() * arr.length)
result.push(arr[index])
arr.splice(index, 1)
}
console.log(result)
发布于 2018-07-05 12:23:15
https://stackoverflow.com/questions/51189639
复制相似问题