Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 주어진 숫자로 합산되는 고유 숫자 쌍의 모든 인덱스 중 가장 작은 합계 찾기

<시간/>

숫자 배열을 첫 번째 인수로, 목표 합계를 두 번째 인수로 취하는 함수를 작성해야 합니다. 그런 다음 배열을 반복한 다음 각 값을 서로 추가하려고 합니다(자체 + 자체 제외).

그리고 반복된 두 값의 합이 목표 합과 같고 값 쌍이 이전에 만난 적이 없는 경우 해당 인덱스를 기억하고 마지막에 기억된 모든 인덱스의 전체 합계를 반환합니다.

배열이 -

인 경우
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