Skip to content

Instantly share code, notes, and snippets.

@laurentpetit
Created December 21, 2011 21:39
Show Gist options
  • Save laurentpetit/1507832 to your computer and use it in GitHub Desktop.
Save laurentpetit/1507832 to your computer and use it in GitHub Desktop.
FooBarQiz in Clojure
;; Note 1: in a real project, would have had 3 files: one for the code, one for the tests, one for the test data
;; Note 2: you can test online at http://tryclj.com/ : copy/paste the (do ...) encapsulating the 3 defs (lines 7 to 21).
;; Then hit Enter to evaluate. Then type (main), then hit Enter to evaluate.
(ns foobarqiz)
(do ;; trick to ease the use of copying/pasting into http://tryclj.com
(def data (sorted-map 7 "Qix", 5 "Bar", 3 "Foo"))
(defn serialize
"Serializes number x into FooBarQiz representation."
[x]
(let [dividers (for [[n s] data :when (zero? (rem x n))] s)
content (for [c (str x) :let [s (data (- (int c) (int \0)))] :when s] s)
r (apply str (concat dividers content))]
(if (.isEmpty r) x r)))
(defn main
([] (main 1 101))
([m M] (doseq [x (range m M)] (println (serialize x)))))
)
(use 'clojure.test)
(require '[clojure.string :as str])
(def first-hundred-results
"1
2
FooFoo
4
BarBar
Foo
QixQix
8
Foo
Bar
11
Foo
Foo
Qix
FooBarBar
16
Qix
Foo
19
Bar
FooQix
22
Foo
Foo
BarBar
26
FooQix
Qix
29
FooBarFoo
Foo
Foo
FooFooFoo
Foo
BarQixFooBar
FooFoo
FooQix
Foo
FooFoo
Bar
41
FooQix
Foo
44
FooBarBar
46
Qix
Foo
Qix
BarBar
FooBar
Bar
BarFoo
FooBar
BarBarBar
QixBar
FooBarQix
Bar
Bar
FooBar
61
62
FooQixFoo
64
BarBar
Foo
Qix
68
Foo
BarQixQix
Qix
FooQix
QixFoo
Qix
FooBarQixBar
Qix
QixQixQix
FooQix
Qix
Bar
Foo
82
Foo
FooQix
BarBar
86
FooQix
88
89
FooBar
Qix
92
FooFoo
94
BarBar
Foo
Qix
Qix
Foo
Bar")
(deftest test-first-hundred
(dorun (map #(assert (= %1 (str (serialize %2)))
(str "expected " %1 ", got " (serialize %2)))
(str/split-lines first-hundred-results)
(range 1 101))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment