从[x,y]坐标中删除重复和镜像



let x=[1,2]、6、3、5、5,544],

让y = [3,4、3、5、2,4,426],

expected_x=[1,2,6,3,5,5,4]
expected_y=[3,4,3,5,2,4,6]

把x和y看作坐标。[1,3]为第一个点[4,6]为最后一个点

如果[X,Y]有重复项,则在预期输出中将只显示一个[X,Y](无重复项)。如果,存在一个类似[X,Y]的镜像,它是[Y,X]的镜像,且两者的索引相同

这是我为一个数组写的代码使数组唯一。然而,我不确定如何使用它与2个单独的数组表示x和y坐标。任何帮助都将是感激的:)

let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [...new Set(chars)];
console.log(uniqueChars);

使用

let x=[1,2,6,3,5,5,5,4,4];
let y=[3,4,3,5,2,4,4,2,6];
const coordinates = [];
let i = -1;
while ( x[++i] ) { 
const c = {
index: i,
value:  [x[i], y[i]]
}
coordinates.push(c);
}
const coordArray = coordinates.reduce((p, next) => {
if (!p.values.includes(JSON.stringify(next.value)) && !p.values.includes(JSON.stringify([...next.value].reverse()))) {
p.values.push(JSON.stringify(next.value));
p.indexes.push(next.index);
}
return p;
},{
indexes: [],
values: []
})
coordArray.values = coordArray.values.map(JSON.parse)
console.log(coordArray)

您可以使用for loop并同时迭代两个数组,因为它们彼此具有相同的长度(作为x,y对)。

你也可以保存一个"历史"。副本和镜像。然后在迭代时需要做的就是检查历史记录。如果没有匹配,将当前值附加到结果数组中,然后更新历史记录。

let x=[1,2,6,3,5,5,5,4,4];
let y=[3,4,3,5,2,4,4,2,6];
let h=[]; // history
let rx = []; // result x
let ry = []; // result y
for (let i = 0; i < x.length && i < y.length; i++) {
// The if line (with include()) would be nice if it worked, but it didn't because of 
// always returning false.
// Instead I will have to manually search.
// if (h.includes([x[i], y[i]]) || h.includes([y[i], x[i]])) {
let found = false;
for (let s = 0; s < h.length; s++) {
// check for duplicate
if (h[s][0] == x[i] && h[s][1] == y[i]) {
found = true;
break;
}
// check for mirror
if (h[s][0] == y[i] && h[s][1] == x[i]) {
found = true;
break;
}
}
if (found) {
// do nothing, its a duplicate or mirror
console.log("duplicate or mirror detected on index " + i);
}
else {
// update results
rx.push(x[i]);
ry.push(y[i]);

// update history
h.push([ x[i], y[i] ]);
}
}
console.log("rx: " + rx);
console.log("ry: " + ry);

简而言之,.include()本来是不错的,但显然,通过引用的数组打破了我的预期逻辑。我不知道。但是上面通过对"历史"的逐字搜索将这些问题分离出来,这将改变"发现"。布尔值,知道是否存在副本或镜像。

显然,这段代码可以缩短到少于10或7行,但我想做它,因为它很有趣,而且所使用的方法演示了如何使用常规for循环来解决这种"迭代"。问题。

希望能有所帮助。

最新更新