我有两个数组: data和usedIndexes。首先,我需要找到所有可除(数组中的另一个数字)数字,并将它们与它们的索引一起存储(比如在myMap中),然后以某种方式遍历第二个数组" usedIndexes“,并找到可分对,其中一个索引号在usedIndexes数组中。
例如,给定数组: data:[8, 3, 5, 2, 7, 9, 50]
usedIndexes = [0, 1, 6]
const myMap = {}
for (let i = 0; i < arr.length; i++) {
for(let y = i + 1; y < arr.length; y++) {
if(arr[i] % arr[y] === 0 || arr[y] % arr[i] === 0 ) {
if(!myMap[i]) {
myMap[i] = arr[i]
}
if(!myMap[y]) {
myMap[y] = arr[y];
}
}
}
}因此,这将给出类似于(索引-值对)、myMap的内容。
{
0: 8,
3: 2,
1: 3,
5: 9,
2: 5,
6: 50
3: 2,
6: 50
}因此,实际的可分拆对如下:
8-2
3-9
5- 50
2- 50
坦率地说,我不确定map/object是否是保存这些值的最佳数据结构,但我想不出其他的东西。
现在,我如何循环遍历usedIndexes数组并找到至少在usedIndexes中有一个的键值对。请阅读下面代码示例中的注释。
for (let i = 0; i < usedIndexes.length; i++){
// e.g. usedIndexes first element is 0 and myMap has 0:8
// but what I need to return 0:8 AND 3:2 because dividable pair is 8 - 2.
}发布于 2022-10-10 04:04:54
不要将除数值存储在映射中,而是存储其索引:
const myMap = {};
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i != j && arr[i] % arr[j] === 0) {
myMap[i] = j;
myMap[j] = i;
}
}
}然后,只需在usedIndexes中找到那些在地图上作为一对的一部分出现的内容:
const result = [];
for (const index of usedIndexes) {
if (index in myMap) {
const other = myMap[index];
result.push([{index, value: arr[index]}, {index: other, value: arr[other]}]);
}
}
console.log(result);但是,这并不能找到所有可能的对,其中一个值被另一个值分开,一个值被usedIndex引用。这是因为myMap只为每个索引存储一个对,即使一个索引将包含在多个索引中。(为了简单起见,我没有费心检查赋值是否会覆盖第一个片段中的其他值,它只会更改第一个或最后一个组合是否会找到,不会解决问题)。
为了缓解这个问题,我们应该摆脱myMap,在嵌套循环中填充result:
const result = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i != j && arr[i] % arr[j] === 0) {
if (usedIndexes.includes(i) || usedIndexes.includes(j)) {
result.push([{index: i, value: arr[i]}, {index: j, value: arr[j]}]);
}
}
}
}
console.log(result);这个解决方案的唯一问题是效率低下-- usedIndexes.includes每次都会迭代usedIndexes数组。您可以通过创建索引的Set来缓解这种情况,然后在循环中使用.has(),但实际上我们可以做得更好:首先不要迭代这些索引!
const result = [];
for (const i of usedIndexes) {
for (let j = 0; j < arr.length; j++) {
if (i != j) {
const [a, b] = arr[i] > arr[j] ? [i, j] : [j, i];
if (arr[a] % arr[b] === 0) {
result.push([{index: a, value: arr[a]}, {index: b, value: arr[b]}]);
}
}
}
}
console.log(result);https://stackoverflow.com/questions/74009767
复制相似问题