首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除[x,y]坐标中的重复和镜像

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

Stack Overflow用户
提问于 2022-04-20 04:16:41
回答 2查看 93关注 0票数 1

设x=1,2,6,3,5,554,4;

设y=3,4,3,5,2,442,6;

代码语言:javascript
复制
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的镜子,两者都在同一指数处。

这是我为one数组编写的使数组惟一的代码。但是,我不确定如何将它与表示x和y坐标的两个独立数组一起使用。(如有任何帮助,将不胜感激:)

代码语言:javascript
复制
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [...new Set(chars)];

console.log(uniqueChars);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-20 04:24:46

用这个:

代码语言:javascript
复制
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)

票数 0
EN

Stack Overflow用户

发布于 2022-04-20 04:45:54

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

您还可以保存副本和镜像的“历史记录”。那么,在迭代时所需要做的就是检查历史记录。如果没有匹配,请将当前添加到结果数组,然后更新历史记录。

代码语言:javascript
复制
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循环来解决这样的“迭代”问题。

希望能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71934036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档