Skip to content

Instantly share code, notes, and snippets.

@x
Last active August 29, 2015 14:15
Show Gist options
  • Save x/eb91cacdc442216668fb to your computer and use it in GitHub Desktop.
Save x/eb91cacdc442216668fb to your computer and use it in GitHub Desktop.
Reading Numbers

The following is a function which, when called without arguments, creates an incrementing sequence of numbers where iterating from n to n+1 takes about 2^n seconds.

(defn slow-nums
  ([]
    (slow-nums 0 0))
  ([n sleep-for]
    (Thread/sleep (* sleep-for 1000))
    (cons n (lazy-seq (slow-nums (inc n) (Math/pow 2 n))))))

Example

;; takes about 5 seconds (2^0 + 2^1 + 2^2)
(take 4 (slow-nums))
;; => (0 1 2 3)

;; print each number and the time it was read forever
(doseq [n (slow-nums)]
  (println n (System/currentTimeMillis)))
;; => 0 1423690218544
;;    1 1423690218544
;;    2 1423690219549
;;    3 1423690223553
;;    4 1423690232558
;;    ...

;; print each number in pairs and the time they were read forever
(doseq [numbers (partition 2 (slow-nums))]
  (println numbers (System/currentTimeMillis)))
;; => (0 1) 1423690273680
;;    (2 3) 1423690278684
;;    (4 5) 1423690303691
;;    (6 7) 1423690364694
;;    ...

Problem 1

Write a function that iterates through the sequence and paritions each number by the minute at which it was read. Then prints the minute and the numbers read during that minute.

Example output (results may vary based on the second you started)

2015-02-11 16:34 (0 1 2 3 4 5)
2015-02-11 16:35 (6)
2015-02-11 16:36 (7 8)
2015-02-11 16:38 (9)
2015-02-11 16:39 (10)
2015-02-11 16:41 (11)
2015-02-11 16:44 (12)

Problem 2

Write a function that, every minute, prints the minute and numbers read that were read minute, including empty sets of numbers.

Example output (results may vary based on the second you started)

2015-02-11 16:34 (0 1 2 3 4 5)
2015-02-11 16:35 (6)
2015-02-11 16:36 (7 8)
2015-02-11 16:37 ()
2015-02-11 16:38 (9)
2015-02-11 16:39 (10)
2015-02-11 16:40 ()
2015-02-11 16:41 (11)
2015-02-11 16:42 ()
2015-02-11 16:43 ()
2015-02-11 16:44 (12)

For both problems, strive to write the most "clojure-esque" solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment