iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 1
0
自我挑戰組

各種筆記系列 第 1

[Kata] Clojure - Day 1

為了熟悉 clojure,刷題練習語法

Get the mean of an array

回傳最接近陣列平均數的整數(無條件捨去),且不會給空陣列
Return the average of the given array rounded down to its nearest integer.
The array will never be empty.

下列為題目的測試:

(ns marks-test
  (:require [clojure.test :refer :all]
            [marks :refer :all]))

(deftest simple-test
  (is (= (get-average [2, 2, 2, 2]) 2))
  (is (= (get-average [1, 5, 87, 45, 8, 8]) 25))
  (is (= (get-average [2,5,13,20,16,16,10]) 11))
  (is (= (get-average [1,2,15,15,17,11,12,17,17,14,13,15,6,11,8,7]) 11)))

Solution 1:

;; (Math/floor m) will return a float & int will coerce to integer

(ns marks)


(defn get-average [marks]
  (int (Math/floor (/ (reduce + marks) (count marks))))
  )

個別使用後發現其實不需要 Math/floor 就可以達到取整數的目的:

  • int 取整數
  • Math/floor 無條件捨去,可以用於整數
  • Math/ceil 無條件進位,可以用於整數
  • Math/round 四捨五入,不能用於整數
(int 1.3)              ;; 1
(int 1.5)              ;; 1
(int 1)                ;; 1

(Math/floor 1.3)       ;; 1.0
(Math/floor 1.5)       ;; 1.0
(Math/floor 1)         ;; 1.0

(int (Math/floor 1.3)) ;; 1
(int (Math/floor 1.5)) ;; 1
(int (Math/floor 1))   ;; 1

(Math/ceil 1.3)        ;; 2.0
(Math/ceil 1.5)        ;; 2.0
(Math/ceil 1)          ;; 1.0

(int (Math/ceil 1.3))  ;; 2
(int (Math/ceil 1.5))  ;; 2
(int (Math/ceil 1))    ;; 1

(Math/round 1.3)  ;; 1
(Math/round 1.5)  ;; 2
(Math/round 1.0)  ;; 1
(Math/round 1)    ;; IllegalArgumentException No matching method found: round  clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:80)

Solution 2:

;; In this case, int can be used when rounded down to nearest integer
(ns marks)

(defn get-average [marks]
  (int (/ (reduce + marks) (count marks))))

Solution 3:

;; (quot m n) is the value of m/n, rounded towards 0 to the nearest integer.
;; m, n need not be integers.

(ns marks)

(defn get-average [marks]
  (quot (apply + marks) (count marks)))

下一篇
[Kata] Clojure - Day 2
系列文
各種筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言