Viết hàm nhận mảng số làm đối số đầu tiên và tổng mục tiêu làm đối số thứ hai. Duyệt mảng, cộng từng cặp (trừ cặp với chính nó). Nếu tổng bằng mục tiêu và cặp chưa gặp, ghi nhớ chỉ số. Cuối cùng trả về tổng tất cả chỉ số đã ghi nhớ.
Ví dụ:
const arr = [1, 4, 2, 3, 0, 5]; const sum = 7;
Kết quả 11 vì:
4 + 3 = 7 (index 1, 3) 5 + 2 = 7 (index 5, 2) 1 + 3 + 2 + 5 = 11
Ví dụ
Mã minh họa:
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));Kết quả
Đầu ra:
11