【心得】
group-by
:(map count (vals (group-by #(= 1 %) [1 -1 -1]))) => (1 2)
但似乎寫不出比較直覺看得懂的方式,後面還要再處理才能比較 list 內的兩個值,所以採用 count filter 的做法【今日湯底】
Task
King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel.
To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year's party. He gave you a list of integers of all the party goers.
Arthur needs you to return true if he needs to invite more women or false if he is all set.
Input/Output
[input] integer array L ($a in PHP)
An array (guaranteed non-associative in PHP) representing the genders of the attendees, where -1 represents women and 1 represents men.
2 <= L.length <= 50
[output] a boolean value
true if Arthur need to invite more women, false otherwise.
(必須通過以下測試)
(ns kata.test
(:require [clojure.test :refer :all]
[kata :refer :all]))
(defn tester [l e]
(testing (str "Testing for " l)
(is (= (invite-more-women l) e))))
(deftest basic-tests
(tester [1 -1 1] true)
(tester [-1 -1 -1] false)
(tester [1 -1] false)
(tester [1 1 1] true))
【我的答案】
(ns kata)
(defn invite-more-women [L]
(let [men-count (count (filter #(= 1 %) L))
women-count (count (filter #(= -1 %) L))]
(> men-count women-count))
)
思路:
【其他人的答案】
(ns kata)
(defn invite-more-women [L]
(> (reduce + L) 0))