프로그래머스(Javascript)/Level 0

[프로그래머스 | 자바스크립트] 겹치는 선분의 길이

사랑하애 2023. 3. 2. 15:02

솔루션

const solution = (lines) => {
  const answer = lines.reduce((a, [x, y]) => {
    for (let i = Math.min(x, y) + 1; i <= Math.max(x, y); i++)
      a[i] = a[i] ? a[i] + 1 : 1;
    return a;
  }, {});
  console.log(Object.values(answer).filter((v) => v > 1).length);

  return Object.values(answer).filter((v) => v > 1).length;
};

솔루션

const solution = (lines) => {
  let line = new Array(200).fill(0);

  lines.forEach(([a, b]) => {
    for (; a < b; a++) line[a + 100]++;
  });

  const answer = line.reduce((a, c) => (c > 1 ? a + 1 : a), 0);
  console.log(answer);

  return answer;
};