Dwarf Name Generator

The local ruby group sends out the Ruby Quiz (with some regularity). This week it was to create a Dwarf Name Generator.

I thought of a fairly simple solution in Clojure pretty quickly, but then it took me a while to implement it. Anyway, here is what I came up with.


; Create a couple of Maps with keys being Integers
(def firstnames {1 "Danby" 2 "Tamreil" 3 "Vash" 4 "Gobu"})
(def lastnames {1 "Dongledorp" 2 "Floopydoo" 3 "Goran" 4 "Zypher"})

; Return a random Integer with a value > 0 but < = the upper bounds
(defn randomize [upper]
(let [randy (. Math round(* (. Math random) upper))]
(if (= randy 0)
(int (+ 1 randy))
(int randy))))

; Since Maps, can be used as Functions that take a key as an argument
; pass those to println
(println (firstnames (randomize (.size firstnames))) (lastnames (randomize (.size lastnames))))

The reason it took me so long is that initially I wasn't casting 'randy' to a Java Integer, and using it as a argument to a Map (which causes the Map to act as a function) was causing the Map to not find it while looking it up. After a bit of head scratching, I asked in #clojure.

Obviously, if I were a linguist, I would have created a lot of maps with just parts of names in them (I am sure that is called something), and then randomized that further, but I am not, and since the underlying mechanics would be more or less the same, I left it as is.

Happy hacking!

About Nathan Powell

I am a middle aged technologist freak-ball.
This entry was posted in programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>