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

JavaScript에서 배열 요소 재정렬

<시간/>

문제

첫 번째이자 유일한 인수로 숫자 배열인 arr을 취하는 JavaScript 함수를 작성해야 합니다.

배열 arr은 항상 짝수 길이입니다.

0 <=i

예를 들어, 함수에 대한 입력이 -

인 경우
const arr = [4, -2, 2, -4];

그러면 출력은 다음과 같아야 합니다. -

const output = true;

출력 설명

[-2,-4] 및 [2,4] 두 그룹을 사용하여 [-2,-4,2,4] 또는 [2,4,-2,-4]를 형성할 수 있습니다.

예시

이에 대한 코드는 -

const arr = [4, -2, 2, -4];
const canRearrange = (arr = []) => {
   const map = arr.reduce((acc, num) => {
      acc[num] = (acc[num] || 0) + 1
      return acc
   }, {});
   const keys = Object.keys(map)
   .map(key => Number(key))
   .sort((a, b) => a - b)
   for (const key of keys) {
      if (key < 0) {
         while (map[key] > 0) {
            if (map[key / 2] > 0) {
               map[key] -= 1
               map[key / 2] -= 1
            } else {
               return false
            }
         }
      } else {
         while (map[key] > 0) {
            if (map[key * 2] > 0) {
               map[key] -= 1
               map[key * 2] -= 1
            } else {
               return false
            }
         }
      }
   }
   return true
};
console.log(canRearrange(arr));

출력

콘솔의 출력은 -

true