我正在尋找一種方法來獲取陣列中兩個陣列項的序列,尤其是長度為 4 的陣列
例如,
[[1,0], [2,3], [5,4], [0,0], [3,2], [1,4], [0,5]]
...應該回傳:
[[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 回圈,但它難以辨認且令人困惑,可能太難了,但這只是計算最長的序列,而不是回傳它:
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
uj5u.com熱心網友回復:
您可以將點添加到物件并通過使用為x和添加偏移量的因子來檢查四個的順序y。
如果需要,您也可以添加對水平或垂直點的檢查。
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; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377962.html
標籤:javascript 数组 排序 多维数组
上一篇:加速我的字串文本替換代碼
