프로그래머스 level 1. 최소직사각형

최소직사각형

문제 설명

명함 지갑을 만드는 회사에서 지갑의 크기를 정하려고 합니다. 다양한 모양과 크기의 명함들을 모두 수납할 수 있으면서, 작아서 들고 다니기 편한 지갑을 만들어야 합니다.

모든 명함의 가로 길이와 세로 길이를 나타내는 2차원 배열 sizes가 매개변수로 주어집니다. 모든 명함을 수납할 수 있는 가장 작은 지갑을 만들 때, 지갑의 크기를 return 하도록 solution 함수를 완성해주세요.

풀이

2차원 배열의 최대값을 찾는 문제.

  1. 두 배열의 요소의 값을 비교한다.
  2. 요소 중 큰 값을 가로로 한다.
  3. 요소 중 작은 값을 세로로 하는 배열을 만든다.
  4. 세로 길이 중 가장 큰 값과 가로 길이 중 가장 큰 값을 곱한다.

map 을 사용한 풀이

function solution(cards) {
  const maxWidth = cards.map(([a, b]) => Math.max(a, b));
  const maxHeight = cards.map(([a, b]) => Math.min(a, b));

  return Math.max(...maxWidth) * Math.max(...maxHeight);
}

for 문을 사용한 풀이

function solution(cards) {
  let arr = [0, 0];

  for (let i = 0; i < cards.length; i++) {
    const [w, h] = cards[i].sort((a, b) => b - a);

    if (w > arr[0]) {
      arr[0] = w;
    }

    if (h > arr[1]) {
      arr[1] = h;
    }
  }

  return arr[0] * arr[1];
}

for…of 를 사용한 풀이

function solution(cards) {
  let width = 0;
  let height = 0;

  for (const [a, b] of cards) {
    width = Math.max(width, Math.max(a, b));
    height = Math.max(height, Math.min(a, b));
  }

  return width * height;
}

forEach 를 사용한 풀이

function solution(cards) {
  let answer = 0;
  let maxOfheight = 0;
  let maxOfwidth = 0;

  cards.forEach(([w, h]) => {
    const [height, width] = [Math.max(w, h), Math.min(w, h)];
    if (height > maxOfheight) maxOfheight = height;
    if (width > maxOfwidth) maxOfwidth = width;
    answer = maxOfheight * maxOfwidth;
  });

  return answer;
}