On Sep 26, 6:13 pm, Jeremy Heiler <jeremyhei...@gmail.com> wrote: > On Mon, Sep 26, 2011 at 9:12 AM, Paul Richards <paul.richa...@gmail.com> > wrote: > > Hi, > > How can I efficiently pick a random element from a sorted-set? > > > If I try rand-nth I get this: > > user=> (rand-nth (sorted-set 1 2 3)) > > java.lang.UnsupportedOperationException: nth not supported on this > > type: PersistentTreeSet (NO_SOURCE_FILE:0) > > > I can get this expression to work if I naively apply seq: > > user=> (rand-nth (seq (sorted-set 1 2 3))) > > 1 > > > However this performs very badly on large sets. Is there a more > > efficient way to do this? > > > (I need to keep my elements in a sorted-set for other parts of the > > application, where I rely on subseq.) > > Try just getting the value with rand-int directly. The sorted-set uses > a tree map underneath, so look up time is consistent with a map. Also, > count is O(1). > > (get foo (rand-int (count foo)))
I feel I picked a bad example. My sorted-set does not contain integers, the elements are (collections of) strings. Trying this approach leads to a different failure: user=> (get (sorted-set "a" "b" "c") 1) java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number (NO_SOURCE_FILE:0) -- 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