हमें एक फंक्शन लिखना है जो नंबरों के ऐरे को पहले आर्गुमेंट और टारगेट योग को दूसरे आर्गुमेंट के रूप में लेता है। फिर हम ऐरे के माध्यम से लूप करना चाहते हैं और फिर प्रत्येक वैल्यू को प्रत्येक अन्य में जोड़ना चाहते हैं (खुद को छोड़कर)।
और यदि लूप किए गए दो वैल्यू का योग टारगेट योग के बराबर है, और वैल्यू का जोड़ा पहले नहीं मिला है, तो हम उनके इंडेक्स याद रखते हैं और अंत में सभी याद किए गए इंडेक्स का पूरा योग लौटाते हैं।
यदि ऐरे है:
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