busStops.js (7kyu 28)

Codewars 알고리즘 풀이


Problem

  • There is a bus moving in the city, and it takes and drop some people in each bus stop.
    • 버스가 각 버스 정류장에서 일부 사람들을 태우거나 내려준다.
  • Each integer array has two items which represent number of people get into bus and number of people get off the bus in a bus stop.
    • 각 정수 배열에는 버스에 타는 사람 수(첫 번째 item)와 내리는 사람 수(두 번째 item)를 나타내는 두 개의 item이 있다.
  • Your task is to return number of people who are still in the bus after the last bus station.
    • 마지막 버스 정류장 후에 여전히 남아 있는 사람 수를 반환한다.


Solution 01

function busStops(arr) {
  let people = 0;
  
  for (let i = 0; i < arr.length; i++) {
    people += arr[i][0];
    people -= arr[i][1];
  }
  return people;
}

busStops([10, 0], [0, 2]);                 // 8
busStops([4, 0], [2, 1], [1, 3], [0, 2]);  // 1


Solution 02

function busStops(arr) {
  let people = 0;
  
  for (let i = 0; i < arr.length; i++) {
    people += arr[i][0] - arr[i][1];
  }
  return people;
}

busStops([10, 0], [0, 2]);                 // 8
busStops([4, 0], [2, 1], [1, 3], [0, 2]);  // 1


Solution 03

function busStops(arr) {
  return arr.reduce((sum, i) => sum + i[0] - i[1], 0);
}

busStops([10, 0], [0, 2]);                 // 8
busStops([4, 0], [2, 1], [1, 3], [0, 2]);  // 1

reduce(): 배열을 하나의 값으로 줄이고, 그 값을 반환한다.


Solution 04

function busStops(arr) {
  return arr.reduce((sum, [into, off]) => sum + into - off, 0);
}

busStops([10, 0], [0, 2]);                 // 8
busStops([4, 0], [2, 1], [1, 3], [0, 2]);  // 1


Solution 05

function busStops(arr) {
  return arr.map(i => i[0] - i[1]).reduce((sum, i) => sum + i);
}

busStops([10, 0], [0, 2]);                 // 8
busStops([4, 0], [2, 1], [1, 3], [0, 2]);  // 1

map(): 배열 내 모든 element에 대해, 호출한 함수의 결과를 모아 새 배열로 반환한다.


Solution 06

function busStops(arr) {
  let getInto = 0;
  let getOff = 0;
  
  arr.forEach(i => {
    getInto += i[0];
    getOff += i[1];
  });
  return getInto - getOff;
}

busStops([10, 0], [0, 2]);                 // 8
busStops([4, 0], [2, 1], [1, 3], [0, 2]);  // 1

forEach(): 배열의 각 element에 대해, 제공된 함수를 차례로 한 번씩 호출한다.