如何不重复索引就从源数组生成随机数组?

时间:2018-07-31 09:10:24

标签: javascript

我已经针对特定情况部署了该算法,我想在这里发布,以便有人可以在他的项目中使用它。 它使用JavaScript,但可以轻松转换为另一种语言。 希望会有用。

fy(Y<int>(2));

1 个答案:

答案 0 :(得分:0)

/* 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]