เราจำเป็นต้องเขียนฟังก์ชันที่รับอาร์เรย์ของตัวเลขเป็นอาร์กิวเมนต์แรกและผลรวมเป้าหมายเป็นอาร์กิวเมนต์ที่สอง จากนั้นเราต้องการวนรอบอาร์เรย์แล้วเพิ่มแต่ละค่าให้กันและกัน (ยกเว้นตัวเอง + ตัวเอง)
และหากผลรวมของสองค่าที่วนซ้ำกันเท่ากับผลรวมเป้าหมาย และไม่เคยพบคู่ของค่ามาก่อน เราก็จำดัชนีของทั้งสองค่านั้นได้ และในตอนท้าย ให้คืนค่าผลรวมทั้งหมดของดัชนีที่จำได้ทั้งหมด
หากอาร์เรย์เป็น −
const arr = [1, 4, 2, 3, 0, 5];
และผลรวมคือ −
const sum = 7;
ดังนั้นผลลัพธ์ควรเป็น 11 เพราะ
4 + 3 = 7 5 + 2 = 7
ดัชนี -
4 [index: 1] 2 [index: 2] 3 [index: 3] 5 [index: 5]
กล่าวคือ
1 + 2 + 3 + 5 = 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