문제
첫 번째이자 유일한 인수로 숫자 배열인 arr을 취하는 JavaScript 함수를 작성해야 합니다.
배열 arr은 항상 짝수 길이입니다.
0 <=i
예를 들어, 함수에 대한 입력이 -
그러면 출력은 다음과 같아야 합니다. -
[-2,-4] 및 [2,4] 두 그룹을 사용하여 [-2,-4,2,4] 또는 [2,4,-2,-4]를 형성할 수 있습니다.
이에 대한 코드는 -
콘솔의 출력은 -const arr = [4, -2, 2, -4];
const output = true;
출력 설명
예시
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