Created
June 13, 2010 11:49
-
-
Save j1n3l0/436599 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Import functions from one of my own modules | |
;;; I think I need to understand/set up CLASSPATH | |
(ns digits) | |
(def digit_map | |
{ \0 0 \1 1 \2 2 \3 3 \4 4 \5 5 \6 6 \7 7 \8 8 \9 9 }) | |
(defn digits-1 | |
"Return the digits of a number as a list" | |
[number] | |
(map #(- (int %) (int \0)) (seq (str number)))) | |
(defn digits-2 | |
"Return the digits of a number as a list" | |
[number] | |
(let [m { \0 0 \1 1 \2 2 \3 3 \4 4 \5 5 \6 6 \7 7 \8 8 \9 9 }] | |
(map #(m %) (seq (str number))))) | |
(defn digits-3 | |
"Return the digits of a number as a list" | |
[number] | |
(reverse (map #(rem % 10) (take-while #(> % 0) (iterate #(quot % 10) number))))) | |
(defn digits-4 | |
"Return the digits of a number as a list" | |
[number] | |
(map #(digit_map %) (seq (str number)))) | |
;;; now let's see which is fastest ... | |
(time (dotimes [_ 100000] (digits/digits-1 1234))) | |
(time (dotimes [_ 100000] (digits/digits-2 1234))) | |
(time (dotimes [_ 100000] (digits/digits-3 1234))) | |
(time (dotimes [_ 100000] (digits/digits-4 1234))) | |
;; "Elapsed time: 58.449 msecs" | |
;; "Elapsed time: 265.609 msecs" | |
;; "Elapsed time: 907.47 msecs" | |
;; "Elapsed time: 57.948 msecs" | |
(println "so 1 and 4 are fastest, let's give em longer strings ...") | |
(time (dotimes [_ 100000] (digits/digits-1 1234567890))) | |
(time (dotimes [_ 100000] (digits/digits-4 1234567890))) | |
;; "Elapsed time: 67.175 msecs" | |
;; "Elapsed time: 67.576 msecs" | |
(println "so it seems 1 is better for longer strings, therefore 1 is the winner ;)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment