javascript - 如何从源数组生成随机数组而不重复索引?
问题描述
我已经针对特定情况部署了这个算法,我想在这里发布,以便有人可以在他的项目中使用它。它在 JavaScript 中,但可以很容易地转换为另一种语言。希望有用。
/* generating a random array from a source array, algorithm */
function createRandomArray(srcArray, amount) {
var rndArray = []; // random array
while (rndArray.length < amount) { // how many random items?
// generating a random index
const random_index = Math.floor(Math.random() * srcArray.length);
// if random array doesn't have random index then...
if (!rndArray.includes(random_index)) {
// push the current item from source array with random inex
rndArray.push(srcArray[random_index]);
// then remove the selected item from source array with random inex
srcArray.splice(random_index, 1);
}
}
return rndArray; // the output of this function is a an array with random items
}
const sourceArray = [1,2,3,4,5,6,7,8,9,0];
print(createRandomArray(sourceArray, 5));
// output [6, 1, 8, 2, 7]
解决方案
/* generating a random array from a source array, algorithm */
function createRandomArray(srcArray, amount) {
var rndArray = []; // random array
while (rndArray.length < amount) { // how many random items?
// generating a random index
const random_index = Math.floor(Math.random() * srcArray.length);
// if random array doesn't have random index then...
if (!rndArray.includes(random_index)) {
// push the current item from source array with random inex
rndArray.push(srcArray[random_index]);
// then remove the selected item from source array with random inex
srcArray.splice(random_index, 1);
}
}
return rndArray; // the output of this function is a an array with random items
}
const sourceArray = [1,2,3,4,5,6,7,8,9,0];
print(createRandomArray(sourceArray, 5));
// output [6, 1, 8, 2, 7]
推荐阅读
- django - Django 1.9中的子查询多对多关系
- git - 来自多个存储库的代码的 GIT 分支
- butterknife - 迁移到 andoidX 后,Butterknife 未绑定对象
- heap-memory - 如何选择钻头以使用偏移量运行查询?
- python - Django 数据存储 - SQL 还是其他?
- sql - 使用计算列将现有表转换为时态表(用户定义函数)
- sparql - 将同义词库与 SPARQL (MarkLogic) 一起使用
- keycloak - Keycloak ID 令牌不包含“组”信息
- javascript - 我想在我无法控制 RTE 元素的 RTE 组件中附加一个 ng-click
- groovy - 从 Groovy 2.4 升级到 2.5 时由于“无法启动片段包”而解决 OSGi 测试?