clojure - Changing 1-3 random index(s) in a sequence to a random value -


i changed value random. example

'(1 2 3 4 5) 

one possible output.

'(1 3 3 4 5) 

another

'(1 5 5 4 5) 

there more idiomatic ways in clojure. example one:

you can generate infinite lazy sequence of random changes initial collection, , take random item it.

(defn random-changes [items limit]   (rest (reductions #(assoc %1 (rand-int (count items)) %2)                     (vec items)                     (repeatedly #(rand-int limit))))) 

in repl:

user> (take 5 (random-changes '(1 2 3 4 5 6 7 8) 100)) ([1 2 3 4 5 64 7 8] [1 2 3 4 5 64 58 8] [1 2 3 4 5 64 58 80]   [1 2 3 4 5 28 58 80] [1 2 3 71 5 28 58 80])  user> (nth (random-changes '(1 2 3 4 5 6 7 8) 100) 0) [1 2 3 64 5 6 7 8] 

and can take item @ index want (so means collection index + 1 changes).

user> (nth (random-changes '(1 2 3 4 5 6 7 8) 100) (rand-int 3)) [1 46 3 44 86 6 7 8] 

or use reduce take n times changed coll @ once:

(defn random-changes [items limit changes-count]   (reduce #(assoc %1 (rand-int (count items)) %2)           (vec items)           (repeatedly changes-count #(rand-int limit)))) 

in repl:

user> (random-changes [1 2 3 4 5 6] 100 3) [27 2 33 4 76 6] 

also can associate changes in vector @ once: (assoc items 0 100 1 200 2 300), can that:

(defn random-changes [items limit changes-count]   (let [items (vec items)         rands #(repeatedly changes-count (partial rand-int %))]     (apply assoc items            (interleave (rands (count items))                        (rands limit))))) 

in repl:

user> (random-changes [1 2 3 4 5 6] 100 3) [1 65 61 44 5 6] 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -