唯一随机数生成器
// 唯一随机数生成器
function uniqueRandom(min, max, count, type = 'integer') {
if (max - min + 1 < count && type === 'integer') {
throw new Error('范围太小,无法生成指定数量的唯一随机整数');
}
const generated = new Set();
const results = [];
while (results.length < count) {
let randomValue;
if (type === 'integer') {
randomValue = Math.floor(Math.random() * (max - min + 1)) + min;
} else {
randomValue = Math.random() * (max - min) + min;
randomValue = parseFloat(randomValue.toFixed(4));
}
const key = type === 'integer' ? randomValue : randomValue.toFixed(4);
if (!generated.has(key)) {
generated.add(key);
results.push(randomValue);
}
}
return results;
}
No comments to display
No comments to display