September 21, 2018
Just Juxt #38: Digits and bases (4clojure #137)
Write a function which returns a sequence of digits of a non-negative number (first argument) in numerical system with an arbitrary base (second argument). Digits should be represented with their integer values, e.g. 15 would be [1 5] in base 10, [1 1 1 1] in base 2 and [15] in base 16.
(ns live.test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]))
(defn digits [n b]
(if (zero? n)
[0]
(loop [n n, digits []]
(if (zero? n)
(reverse digits)
(let [[res rm] ((juxt #(quot % b) #(rem % b)) n)]
(recur res (conj digits rm)))))))
(deftest digits-test
(is (= [1 2 3 4 5 0 1] (digits 1234501 10)))
(is (= [0] (digits 0 11)))
(is (= [1 0 0 1] (digits 9 2)))
(is (= [1 0] (let [n (rand-int 100000)](digits n n)))))
(run-tests)