scoop:scoop.std:0.1.0
src/collections/random.scoop
Selected production source · src/collections/random.scoop
1
package scoop.collections3
import scoop.random.Random5
/**6
* Selects one element using the supplied random source, or returns None for empty input.7
*/8
public fun <T> List<T>.randomOrNone(random: Random): T? {9
val count = size10
if (count == 0L) return None11
return Some(this[if (count == 1L) 0L else random.nextLong(count)])12
}14
/**15
* Selects one element using the supplied random source, or returns None for empty input.16
*/17
public fun <T> Iterable<T>.randomOrNone(random: Random): T? {18
var selected: T? = None19
var count = 0L20
for (value in this) {21
if (count == Long.MAX_VALUE) throw ArithmeticException()22
count += 1L23
if (count == 1L || random.nextLong(count) == 0L) selected = Some(value)24
}25
return selected26
}28
/**29
* Selects one element using the supplied random source; empty input throws NoSuchElementException.30
*/31
public fun <T> List<T>.random(random: Random): T = when (randomOrNone<T>(random)) {32
case Some(val value) -> value33
case None -> throw NoSuchElementException("empty collection")34
}36
/**37
* Selects one element using the supplied random source; empty input throws NoSuchElementException.38
*/39
public fun <T> Iterable<T>.random(random: Random): T = when (randomOrNone<T>(random)) {40
case Some(val value) -> value41
case None -> throw NoSuchElementException("empty iterable")42
}44
/**45
* Permutes this mutable list in place using the supplied random source.46
*/47
public fun <T> MutableList<T>.shuffle(random: Random) {48
var count = size49
while (count > 1L) {50
val chosen = random.nextLong(count)51
count -= 1L52
if (chosen != count) {53
val last = this[count]54
this[count] = this[chosen]55
this[chosen] = last56
}57
}58
}60
/**61
* Copies the elements into a randomly permuted list using the supplied random source.62
*/63
public 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())67
}