Created
September 1, 2011 17:36
-
-
Save prajwalit/1186723 to your computer and use it in GitHub Desktop.
[4clojure #108] Given any number of sequences, each sorted from smallest to largest, find the smallest number which appears in each sequence. The sequences may be infinite, so be careful to search lazily.
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
(defn smallest-common-number [& seqs] | |
(letfn [;; Get max of first items of seqs | |
(max-first [seqs] | |
(apply max (map first seqs))) | |
;; Test if first elemets are equal | |
(first-equal? [seqs] | |
(apply = (map first seqs))) | |
;; Filter values less than x | |
(update-seq [x coll] | |
(if (> x (first coll)) | |
(update-seq x (rest coll)) | |
coll))] | |
(let [curr (max-first seqs)] | |
(if (first-equal? seqs) | |
curr | |
(apply smallest-common-number (map #(update-seq curr %) seqs)))))) | |
(smallest-common-number [1 2 3 4 5 12 18] [-1 5 10 12] [3 12 17]) | |
;; => 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment