Finding neighbours in a two-dimensional array

后端 未结 20 1196
忘了有多久
忘了有多久 2020-11-30 02:02

Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding

20条回答
  •  情歌与酒
    2020-11-30 02:23

    In javascript

        let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
            function getNeighborsNumbersAtIthJth(i, j) {
                let allPosibleIndexes = [
                    [i - 1, j],
                    [i, j - 1],
                    [i - 1, j - 1],
                    [i + 1, j],
                    [i, j + 1],
                    [i + 1, j + 1],
                    [i + 1, j - 1],
                    [i - 1, j + 1]
                ];
                let allPosibleValues = []
                allPosibleIndexes.forEach(([i, j]) => {
                    try {
                        allPosibleValues.push(arr[i][j])
                    } catch (err) {
    
                    }
                })
                return allPosibleValues.filter(v => v != undefined);
            }
            console.log(getNeighborsNumbersAtIthJth(1, 1));//[2, 4, 1, 8, 6, 9, 7, 3]
            console.log(getNeighborsNumbersAtIthJth(0, 1));//[1, 5, 3, 6, 4]
            console.log(getNeighborsNumbersAtIthJth(0, 0));//[4, 2, 5]
    

提交回复
热议问题