Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It often helps to break the problem into layers that can be solved independently. Augment does this nicely in assigning ranges, though the result is harder to consume with the normal sequence functions while choosing one at random. If you change the goal of augment to have it produce a normal seq then the augmentation problem is more cleanly separated from choosing one randomly. Provided the weights are integers you can build a list containing weight number of each item, and then choose one at random:</p> <pre><code>user&gt; (map (fn [[item weight]] (repeat weight item)) colors) ((:white) (:red :red :red :red :red :red :red :red :red :red) (:blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue) (:green) (:yellow)) </code></pre> <p>then flatten it down to a single list:</p> <pre><code>user&gt; (flatten (map (fn [[item weight]] (repeat weight item)) colors)) (:white :red :red :red :red :red :red :red :red :red :red :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :blue :green :yellow) </code></pre> <p>and pick one with <code>rand-nth</code>:</p> <pre><code>user&gt; (rand-nth (flatten (map (fn [[item weight]] (repeat weight item)) colors))) :blue </code></pre> <hr> <p>ps: map literals make things look better: <a href="http://clojure.org/reader" rel="nofollow">the reader page</a> describes these nicely</p> <pre><code>(def colors {:white 1, :red 10, :blue 20, :green 1, :yellow 1}) </code></pre> <p>use let to give things names within functions:</p> <pre><code>(defn augment [x] (let [name (nth x 0) val (nth x 1) newval (+ cur val) left cur right newval cur (+ cur val)] [name left right])) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload