Thursday, February 4, 2016

Kata: Wonderland Number in Clojure

I just redid the Wonderland Number kata from Carine Meier's Living Clojure book that we did this week at a Clojure Developers Barcelona event.

These are the tests using Midje:

(ns wonderland-number.finder-test
(:require [midje.sweet :refer :all]
[wonderland-number.finder :as finder]))
(defn same-digits-as [num]
(fn [multiple]
(= (set (str num)) (set (str multiple)))))
(defn digits-number [num]
(count (str num)))
(facts
"about Wonderland number"
(let [wondernum (finder/find-wonderland-number)]
(fact
"it has six digits"
(digits-number wondernum) => 6)
(fact
"it contains the same digits that its multiples by 2, 3, 4, 5 and 6"
(* 2 wondernum) => (same-digits-as wondernum)
(* 3 wondernum) => (same-digits-as wondernum)
(* 4 wondernum) => (same-digits-as wondernum)
(* 5 wondernum) => (same-digits-as wondernum)
(* 6 wondernum) => (same-digits-as wondernum))))
and this is the final code:

(ns wonderland-number.finder)
(def ^:private six-digts-nums
(range 100000 1000000))
(defn- digits [num]
(set (str num)))
(defn- same-digits? [num1 num2]
(= (digits num1) (digits num2)))
(defn- multiples [num]
(map #(* num %) [2 3 4 5 6]))
(defn- wonder? [num]
(every? (partial same-digits? num) (multiples num)))
(defn find-wonderland-number []
(first (filter wonder? six-digts-nums)))
I just played in the REPL to do it.

You can find all the code on GitHub.

No comments:

Post a Comment