(defn sleepsort [& s] (deref (reduce #(do (await (deref %2)) (deref
%2)) nil  (doall (map #(future (Thread/sleep (* %1 100)) (send %2 conj
%1) %2) s (repeat (agent [])))))))

user=>(sleepsort 2 1 6 5)
[1 2 5 6]

By having the future return the agent, the reduce then calls deref on
all the futures and returning the agent.  The agent itself is then
deref to get the actual result.

There you have it, an O(n) sort algorithm.  Of course with the
indeterminancy of threads, it would be best if the sequence were
already sorted before calling this function.

On Jun 17, 1:30 pm, Daniel Gagnon <redalas...@gmail.com> wrote:
> I found on Twitter the implementation of the latest stupid algorithm: sleep
> sort. The idea behind sleep sort is that you sleep in parallel for a number
> of second equal to the value of each cell and emit them as you finish
> sleeping. The algorithm is said to run in O(lol^n)
>
> The canonical implementation is:
>
> #!/bin/bashfunction f() {
>     sleep "$1"
>     echo "$1"}while [ -n "$1" ]do
>     f "$1" &
>     shiftdonewait
>
> I found a clojure version on twitter:
>
> (pmap #(do (Thread/sleep (* %1 1000)) (println %1)) '(5 1 3 6 2))
>
> But I wasn't satisfied with it as it directly prints the list and doesn't
> return a useful value.
> So here's my version:
>
> (defn sleep-sort [coll]
>   (let [result (agent [])
>         coll-length (count coll)]
> (dorun (pmap #(do
>        (Thread/sleep (* % 1000))
>        (send result conj %)) coll))
>  (while (not= (count @result) coll-length) (Thread/sleep 1000))
> @result))
>
> How would you implement it?

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to