[CodeKata JS] SpeedCode #2 - Array Madness

ryan·2021년 2월 20일
0

CodeKata JS

목록 보기
3/26
post-thumbnail

Task

정수가 있는 두 개의 배열 a, b, 둘 다 length >= 1인 배열이 주어지면 배열 a에있는 각 요소의 제곱의 합이 배열 b에있는 각 요소의 세제곱의 합보다 크면 true를 반환하는 프로그램을 만듭니다.

예시)

arrayMadness([4, 5, 6], [1, 2, 3]); // true를 반환합니다. 값이 다음과 같기 떄문입니다. 4 ** 2 + 5 ** 2 + 6 ** 2 > 1 ** 3 + 2 ** 3 + 3 ** 3

Initial Setting

function arrayMadness(a, b) {
  // Ready, get set, GO!!!
}

My Solution

function arrayMadness(a, b) {
  let sumA = a.map(num => num ** 2);
  let sumB = b.map(num => num ** 3);

  sumA = sumA.reduce((x, y) => x + y, 0);
  sumB = sumB.reduce((x, y) => x + y, 0);

  return sumA > sumB ? true : false;
}

Solution 1 of Another User(???)

const sumPwrs = (a, p) => a.reduce( (s, n) => s + n ** p, 0);
const arrayMadness = (a, b) => sumPwrs(a, 2) > sumPwrs(b, 3);
// 이해가 잘 안되는데, 이렇게 적용되는 게 맞는건가...
let a = [4, 5, 6]
let b = [1, 2, 3]

const sumPwrs = (a, p) => a.reduce( (s, n) => s + n ** p, 0);
console.log(sumPwrs(a, 2)) // 77
// 0 + 4 ** 2
// 16 + 5 ** 2
// 41 + 6 ** 2
// 77

console.log(sumPwrs(b, 2)) // 14
// 0 + 1 ** 2
// 1 + 2 ** 2
// 5 + 3 ** 2
// 14

Solution 2 of Another User

// 함수 선언식(function declaration)
function arrayMadness(a, b) {
  return a.reduce((sum, el) => sum + el ** 2, 0) > b.reduce((sum, el) => sum + el ** 3, 0);
}

// 함수 표현식(function expression)
const arrayMadness = (a, b) => a.reduce((acc, x) => acc + x ** 2, 0) > b.reduce((acc, x) => acc + x ** 3, 0);

Array.prototype.reduce()

reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환한다.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // 10

// 5 + 1 + 2 + 3 + 4
console.log(array1. reduce(reducer, 5)); // 15

링크

profile
👨🏻‍💻☕️ 🎹🎵 🐰🎶 🛫📷

0개의 댓글