search

Home  >  Q&A  >  body text

javascript - js crosses two-dimensional arrays to get random numbers. How to achieve average random numbers?

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中文网2728 days ago1533

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-07-05 11:09:26

    The condition is that the top, bottom, left and right are not adjacent. Assuming that the starting point coordinate is (0,0), then the following points (-1, 0), (0, -1), (1, 0), (0, 1) are masked. The characteristics of these points are: the absolute value of x plus the absolute value of y equals 1. Random x and y coordinate values ​​within a reasonable range and add the absolute values ​​of each. If it is not equal to 1 and this coordinate has not been taken before, it is legal.

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 11:09:26

    Here is a very simple hack idea that fully meets the needs, that is, deliberately [taking numbers at cross-sections] to achieve the requirement of [not adjacent to the top, bottom, left, and right]. It only requires two lines:

    function pick (arr) {
      // 若数组长度为 5,则该下标 x 的范围为 1~3
      // 直接依次取 a[x - 1], a[x], a[x + 1] 中交错的项即可
      // 为了保证不越界而根据数组长度限制 x 取值范围
      const pickedIndex = Math.max(
        0, parseInt(Math.random() * arr.length - 2)
      ) + 1
      // 第二维下标交错着 0 1 取值,达到数字不相交的需求
      return [
        arr[pickedIndex - 1][0],
        arr[pickedIndex][1],
        arr[pickedIndex + 1][0]
      ]
    }

    reply
    0
  • Cancelreply