如何获得数组中两个数组项的序列?

How can I get a sequence of two array items in an array?

我正在寻找一种方法来获取数组中两个数组项的序列,尤其是长度为 4 的数组

例如,

[[1,0], [2,3], [5,4], [0,0], [3,2], [1,4], [0,5]]

... 应该 return :

[[3,2], [2,3], [1,4], [0,5]]

3 --^ 2 -----^ 1 ----^ 0 -----^ 所以 [3, 2, 1, 0] 对于 x

[[3,2], [2,3], [1,4], [0,5]]

2 -----^ 3 -----^ 4 ----^ 5 -----^ 所以 [2, 3, 4, 5] y

[[x1, y1], [x2, y2], [x3, y3], [x4, y3]]
// +1 or -1 for the first index
// and +1 or -1 for the second index
[[3,2], [2,3], [1,4], [0,5]] // is a sequence
[[0,0], [1,1], [2,2], [3,3]] // is a sequence
[[4,4], [3,3], [2,2], [1,1]] // is a sequence
[[4,3], [3,3], [2,2], [1,1]] // is not a sequence
[[1,2], [2,3], [4,5], [5,6]] // is a sequence

我尝试使用 for 循环,但它难以辨认且令人困惑,可能太难了 而这只是计算最长的序列,而不是 returning :

const Z = x.sort((a, b) => a - b).reduce((count, val, i) => {
  return count += val + 1 === x[i + 1] ? 1 : 0
}, 1);
const Z2 = y.sort((a, b) => a - b).reduce((count, val, i) => {
  return count += val + 1 === y[i + 1] ? 1 : 0
}, 1);
      
console.log(Z, Z2) // 4 4

您可以将点添加到对象并使用为 xy.

添加偏移量的因子来检查四的顺序

如果需要,您也可以添加对水平点或垂直点的检查。

const
    four = array => {
        const
            data = array.reduce((r, [x, y]) => ((r[x] ??= {})[y] = true, r), {}),
            check = ([x, y], i, j) => {
                const temp = [];
                for (let k = 0; k < 4; k++, x += i, y += j) {
                    if (data[x]?.[y]) temp.push([x, y]);
                    else break;
                }
                if (temp.length === 4) return temp;
            };
            
        let result;
        array.some(p => result = check(p, 1, 1) || check(p, -1, 1));
        return result;
    },
    data = [[1, 0], [2, 3], [5, 4], [0, 0], [3, 2], [1, 4], [0, 5]];

console.log(four(data)); // [[3, 2], [2, 3], [1, 4], [0, 5]]
.as-console-wrapper { max-height: 100% !important; top: 0; }