Wishful Coding

Didn't you ever wish your
computer understood you?

8 ways to tell how many Xes are in a list

Inspired by a question on #clojure. There we go.

mrBliss(1):

(count (filter #{1} '(1 2 4 5 1 5 2))) ; Use this

Raynes:

(count ((group-by identity [1 2 3 4 5 1 5 2]) 1))

Me(1):

(get (frequencies [1 2 3 1 2 3]) 1) ; Or this

Me(2):

(reduce #(if (= %2 1) (inc %1) %1) 0 [1 2 3 2 3 1])

Me(3)

(count (nth (partition-by identity (sort [ 1 2 3 1 2 3])) 0))

mrBliss(2):

(count (remove (complement #{1}) '(1 2 3 1 2 3))) ; But don't ever do this

_ato(1):

((fn f [[x & xs :as coll]] (cond (= coll '(1)) 1, (nil? xs) 0, :else (apply + (map #(f (take-nth 2 %)) [coll xs])))) [1 2 3 4 5 1 5 2])

_ato(2):

(let [s (sort [1 2 3 4 5 1 5 2])] (- (.lastIndexOf s 1) (.indexOf s 1) -1))

But at least Clojure has an awesome and helpful community!

Published on