Scoop API

scoop:scoop.std:0.1.0

src/collections/random.scoop

Selected production source · src/collections/random.scoop

1package scoop.collections
3import scoop.random.Random
5/**
6 * Selects one element using the supplied random source, or returns None for empty input.
7 */
8public fun <T> List<T>.randomOrNone(random: Random): T? {
9 val count = size
10 if (count == 0L) return None
11 return Some(this[if (count == 1L) 0L else random.nextLong(count)])
14/**
15 * Selects one element using the supplied random source, or returns None for empty input.
16 */
17public fun <T> Iterable<T>.randomOrNone(random: Random): T? {
18 var selected: T? = None
19 var count = 0L
20 for (value in this) {
21 if (count == Long.MAX_VALUE) throw ArithmeticException()
22 count += 1L
23 if (count == 1L || random.nextLong(count) == 0L) selected = Some(value)
24 }
25 return selected
28/**
29 * Selects one element using the supplied random source; empty input throws NoSuchElementException.
30 */
31public fun <T> List<T>.random(random: Random): T = when (randomOrNone<T>(random)) {
32 case Some(val value) -> value
33 case None -> throw NoSuchElementException("empty collection")
36/**
37 * Selects one element using the supplied random source; empty input throws NoSuchElementException.
38 */
39public fun <T> Iterable<T>.random(random: Random): T = when (randomOrNone<T>(random)) {
40 case Some(val value) -> value
41 case None -> throw NoSuchElementException("empty iterable")
44/**
45 * Permutes this mutable list in place using the supplied random source.
46 */
47public fun <T> MutableList<T>.shuffle(random: Random) {
48 var count = size
49 while (count > 1L) {
50 val chosen = random.nextLong(count)
51 count -= 1L
52 if (chosen != count) {
53 val last = this[count]
54 this[count] = this[chosen]
55 this[chosen] = last
56 }
57 }
60/**
61 * Copies the elements into a randomly permuted list using the supplied random source.
62 */
63public fun <T> Iterable<T>.shuffled(random: Random): List<T> {
64 val result = toMutableList<T>()
65 result.shuffle<T>(random)
66 return ListSnapshot<T>(result.toArray())