【心得】
終於把 practice / test code 搬到 local 搭配 REPL 工具,好處是每次改完 就能直接 evaluate 看結果對不對(如下圖)
雖然今天題目不難,但在 clojure 裡要解決問題的同時,思考如何用 data structure 呈現出第一眼就好理解的 solution 就不容易了。覺得自己寫的第二種方式還不錯,不輸 best practice 呀XD
【今日湯底】
Clock shows h hours, m minutes and s seconds after midnight.
Your task is to write a function which returns the time since midnight in milliseconds.
Example:
h = 0
m = 1
s = 1
result = 61000
Input constraints:
0 <= h <= 23
0 <= m <= 59
0 <= s <= 59
(必須通過以下測試)
(ns kata.test
(:require [clojure.test :refer :all]
[kata :refer [past]]))
(defn tester [h m s e]
(testing (str "(past " h " " m " " s ")")
(is (= (past h m s) e))))
(deftest basic-tests
(tester 0 1 1 61000)
(tester 1 1 1 3661000)
(tester 0 0 0 0)
(tester 1 0 1 3601000)
(tester 1 0 0 3600000))
【我的答案】
(ns kata)
(defn past [h m s]
(* 1000 (+ (* h 3600) (* m 60) s)))
)
(ns kata)
(defn past [h m s]
(->
(+ (* h 3600) (* m 60) s)
(* 1000))
)
思路:
【其他人的答案】
(ns kata)
(defn past [h m s]
(+
(* s 1000)
(* m 60000)
(* h 3600000)))
(ns kata)
(defn past [h m s]
(->> h (* 60) (+ m)
(* 60) (+ s)
(* 1000)))