对于给定的位置,您可以确定它的所有邻居:
function neighbours(arr, x, y, value){
const result = [];
for(const [dx,dy] of [[1, -1], [1, 0], [1, 1], [0, -1], [0, 1], [-1, -1], [-1,0], [-1, 1]])
if(arr[x + dx] && (y + dy) in arr[x + dx])
result.push(arr[x + dx][y + dy]);
return result;
}
现在在生成二维数组时,我们可以随机选择值,不包括所有直接邻居:
const random = arr => arr[Math.floor(Math.random() * arr.length)];
const set = Array.from({length: 100}, (_, i) => i);
const result = [];
for(let x = 0; x < 10; x++) {
result[x] = [];
for(let y = 0; y < 10; y++) {
const exclude = neighbours(result, x, y);
result[x][y] = random(set.filter(el => !exclude.includes(el)));
}
}
现在数字不会作为直接邻居重复。您可以将其扩展到 neighbours neighbours 等等。