每日一道codewars——Number of People in the Bus【7kyu】

422 阅读2分钟

题目:Number of People in the Bus

题目描述:

There is a bus moving in the city, and it takes and drop some people in each bus stop.

You are provided with a list (or array) of integer arrays (or tuples). Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.

Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D

Take a look on the test cases.

Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative.

The second value in the first integer array is 0, since the bus is empty in the first bus stop.

样例

[[10,0],[3,5],[5,8]] => 5

个人部分

解题思路:

题目也很简单。直接遍历数组中的每个元素,每个元素都是数组,然后数组两元素相减(因为第一个是上车人数,第二个是下车人数)。然后将每次运算结果相加就可以。这里我使用了map配合reduce来完成功能的。

代码:

var number = function (busStops) {  
  return busStops.map(x=>x[0]-x[1]).reduce((a,b)=>a+b)
}

其他部分

其他大佬解法

1. reduce进阶用法

JS的reduce可以接受一个callback参数和一个initialValue参数。其功能如下(截取至MDN)

image.png 此处注意两点

  • 回调函数的第一个参数是累计器累计回调的返回值,即对于数组的每个元素执行完回调函数后,其累计结果将会保存在这个参数中。如果设置了initialValue则该参数初始值为initialValue的值
  • 如果提供了initialValue则回调函数的使用将从0开始,否则将从索引为1开始。 因此代码如下:
var number = function (busStops) {  
  return busStops.reduce((x,[a,b])=>x+a-b,0)
}