August 12, 2018

4clojure 137 - Digits and bases

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 run-tests]]))

(defn db [n base]
  (reverse ((fn digits [n]
              (lazy-seq
               (let [[q r] ((juxt quot rem) n base)]
                 (cons r (when (pos? q)
                           (digits q))))))
            n)))

(deftest test-137
  (is (= [1 2 3 4 5 0 1] (db 1234501 10)))
  (is (= [0] (db 0 11)))
  (is (= [1 0 0 1] (db 9 2)))
  (is (= [1 0] (let [n (rand-int 100000)](db n n))))
  (is (= [16 18 5 24 15 1] (db 2147483647 42)))) ;Integer.MAX_VALUE

(run-tests)  
Tags: coding exercises KLIPSE 4clojure Clojure