Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns cljutils.math
- "Functions for doing stuff")
- (defn- powers-of [n]
- "For given base n, create lazy sequence of powers of n"
- (iterate #(* % n) 1))
- (defn- char-range [& limits]
- "Given an even number of limit characters, creates an inclusive character sequence"
- (apply concat (map (fn [[start end]]
- ;; Partition pairs, convert to ints, map back to chars
- (map char (range (int start)
- (inc (int end))))) (partition 2 limits))))
- (defn- syms-vals [base]
- "Given a base, return the number of characters necessary for representation. Limit is 36 (0-z)"
- ;; Take only the necessary number of characters for the base, then zip with decimal values
- (let [syms (take base (char-range \0 \9 \A \Z))
- vals (range 0 (inc (count syms)))]
- (zipmap syms vals)))
- (defn- prep-str [s base]
- "Maps characters to values, ignoring unrecognized characters."
- (let [charmap (syms-vals base)]
- ;; Convert to upper case, filter out unknown chars, map to values
- (map charmap (filter #(contains? charmap %) (reverse (-> s .toUpperCase))))))
- (defn strton [s base]
- "Given string s and int base, convert to integer"
- ;; Multiply pairs of powers and values, then sum them
- (reduce + (map (fn [[pow val]]
- ;; Create pairs of powers and values
- (* pow val)) (partition 2 (interleave (powers-of base) (prep-str s base))))))
- ;;; Binary
- (strton "0111010110100" 2)
- ;;; octal
- (strton "7264" 8)
- ;;; hex with uppercase
- (strton "EB4" 16)
- ;;; hex
- (strton "eb4" 16)
- ;;; hex with spurious chars
- (strton "eb4" 16)
- ;;; hex with preceding 0x
- (strton "0xEB4" 16)
- ;;; undecimal
- (strton "5a2", 11)
Add Comment
Please, Sign In to add comment