อาร์เรย์: [1, 4, 2, 3, 0, 5] target sum: 7
หาคู่ที่รวมได้ 7 ไม่ซ้ำคู่ (unique pairs) รวมดัชนีของทุกคู่
คู่: 4+3 (index 1,3), 5+2 (index 5,2) → ผลรวมดัชนี = 1+3+5+2 = 11
ตัวอย่างโค้ด
const arr = [1, 4, 2, 3, 0, 5];
const findIndexSum = (arr = [], sum = 0) => {
let copy = arr.slice(0);
const used = [];
let index = 0, indexFirst = 0, indexSecond, first, second;
while (indexFirst < copy.length) {
indexSecond = indexFirst + 1;
while (indexSecond < copy.length) {
first = copy[indexFirst];
second = copy[indexSecond];
if (first + second === sum) {
used.push(first, second);
copy = copy.filter(el => first !== el && second !== el);
indexFirst--;
break;
}
indexSecond++;
}
indexFirst++;
}
const indexSum = used.sort().reduce((acc, val, ind) => {
const fromIndex = ind === 0 || val !== used[ind - 1] ? 0 : index + 1;
index = arr.indexOf(val, fromIndex);
return acc + index;
}, 0);
return indexSum;
};
console.log(findIndexSum(arr, 7));ผลลัพธ์
11
คำอธิบาย: อัลกอริทึม: คัดลอกอาร์เรย์ หาคู่ที่รวมได้ target เก็บค่าที่ใช้แล้ว ลบออกจาก copy (กันซ้ำ) คำนวณดัชนีต้นทางจากอาร์เรย์เดิม รวมดัชนีทั้งหมด