讓 x=[1, 2 ,6,3,5, 5 , 5 , 4 ,4];
讓 y=[3, 4 ,3,5,2, 4 , 4 , 2 ,6];
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] 的鏡像,兩者的索引相同。
這是我為一個陣列撰寫的代碼,以使陣列獨一無二。但是,我不確定如何將它與表示 x 和 y 坐標的 2 個單獨的陣列一起使用。任何幫助將不勝感激 :)
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = [...new Set(chars)];
console.log(uniqueChars);
uj5u.com熱心網友回復:
用這個:
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)
uj5u.com熱心網友回復:
您可以使用 afor 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回圈來解決此類“迭代”問題。
希望它有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459707.html
標籤:javascript html 数组 算法 排序
上一篇:回傳3個值中間的函式?
