iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
Software Development

clojure 30 days系列 第 10

clojure 30 days - day 8

  • 分享至 

  • xImage
  •  

Problem Description

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 pairs. Elements of each
pair 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.

Note

  • keywords: reduce / fn / destructuring
; ruduce function => (reduce f init coll)
(reduce
  (fn [accumulator current-item] ...)
  initial-value
  collection)
  • fn → 執行的函式

    • 必須接受兩個參數:
      • 累積值 (accumulator)
      • 集合裡的當前元素 (current item)
    • 並回傳新的累積值。
  • init → 起始值 (initial value)

    • 一開始的累積值,還沒有處理任何元素前的狀態。
  • coll → 集合 (collection)

    • 會依序把裡面的元素丟給 fn。

Implementation

; fn => anonymous function
; 0 => init (total)
; bus-stops => coll
(defn number [bus-stops]
  (reduce (fn [total [on off]] (+ total (- on off))) 
          0                                          
          bus-stops))                                

; (fn [total [on off]] ...)
; 第一個是 total(acc 累積值)
; 第二個是 current-item(這裡是一對 [on off])

(defn tester [bus-stops exp]
  (= exp (number bus-stops)))

(comment
  (tester [[10 0] [3 5] [5 8]] 5)
  (tester [[3 0] [9 1] [4 10] [12 2] [6 1] [7 10]] 17)
  (tester [[3 0] [9 1] [4 8] [12 2] [6 1] [7 8]] 21))

Other Answers

(defn number
  [bus-stops]
  (reduce - (apply map + bus-stops)))

上一篇
clojure 30 days - day 7
下一篇
clojure 30 days - day 9
系列文
clojure 30 days11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言