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()
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.
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: