random-sample randomly lets each element through with a supplied probability, returning a lazy sequence. With 0.5, each item has a 50% chance of appearing; the result is not guaranteed to contain half the input. section 8.3.3
Its contract is:
- Call (random-sample prob coll) to sample a collection, or call (random-sample prob) to obtain an equivalent transducer. section 8.3.3 section 7.2
- Treat probabilities below 0 as 0% and above 1 as 100%; a nonnumeric probability raises ClassCastException. section 8.3.3
- Expect a variable output size: use another algorithm, such as reservoir sampling, when an exact sample size k is required. section 8.3.3
Sampling and transducer composition
(random-sample 0.5 (range 10)) ;; (1 2 7) (defn x-flip [n] (comp (take n) (random-sample 0.5))) (into [] (x-flip 10) (interleave (repeat "head") (repeat "tail"))) ;; ["head" "head" "tail" "head" "tail" "head" "tail" "tail"] section 8.3.3
Generating a fixed-length password
A low probability may produce too few items from a finite input. Repeating the alphabet with cycle and taking the desired length makes a compact password generator: (->> (cycle alphabet) (random-sample 0.01) (take 10) (apply str)) ;; "C3pu@Y6Xhm" section 8.3.3
Listing 8.12. → Random Selection
(random-sample ([prob]) ([prob coll]))
Use the arity listing to distinguish direct collection sampling from the transducer form. section 8.3.3
