首页 > 解决方案 > 如何从源数组生成随机数组而不重复索引?

问题描述

我已经针对特定情况部署了这个算法,我想在这里发布,以便有人可以在他的项目中使用它。它在 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]

标签: 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]

推荐阅读