javascript - js crosses two-dimensional arrays to get random numbers. How to achieve average random numbers?
PHP中文网
PHP中文网 2017-07-05 11:07:26
0
2
1374

There is a two-dimensional array, how to get 2 or 3 random numbers from a cross (not adjacent to the top, bottom, left, and right)?

Array:

var a = [
    [0, 1],
    [2, 3],
    [4, 5],
    [6, 7]
];

I wrote one like this, but it feels very rigid. The numbers obtained are not even and the code is a bit bloated. Does anyone have a better solution?

function select() {
    var a = [
        [0, 1],
        [2, 3],
        [4, 5],
        [6, 7]
    ];

    var lastSelect = -1;

    for (var i = 0; i < a.length; i++) {

        var index = getRandomNumber(lastSelect, a[i].length);

        console.log(a[i][index]);

        lastSelect = index;
    }

}

function getRandomNumber(lastSelect, max) {

    var random = Math.floor(Math.random() * max);

    if (random == lastSelect) return getRandomNumber(lastSelect, max);

    else return random;

}

select()
PHP中文网
PHP中文网

认证0级讲师

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!