std.rand.Shuffle
class pub Shuffle
A type for sorting arrays in a random order.
Static methods
from_int
Show source codeHide source code
fn pub static from_int(seed: Int) -> Shuffle {
Shuffle(Random.from_int(seed))
}
fn pub static from_int(seed: Int) -> Shuffle
Returns a new Shuffle
that uses the given seed for sorting values.
new
Show source codeHide source code
fn pub static new -> Shuffle {
Shuffle(Random.new)
}
fn pub static new -> Shuffle
Returns a new Shuffle
that sorts values in a random order.
Instance methods
sort
Show source codeHide source code
fn pub mut sort[T](array: mut Array[T]) {
# Note that the types produced by `inko_array_get()` and `inko_array_set()`
# are `Any`. These values aren't dropped automatically, so there's no need
# to mark them as moved to prevent them from being dropped after the swap.
let mut swap = array.size - 1
while swap > 0 {
array.swap_indexes(swap, with: @rng.int_between(min: 0, max: swap))
swap -= 1
}
}
fn pub mut sort[T](array: mut Array[T])
Sorts the values of the given Array
in place such that they are in a
random order.
The algorithm used by this method is Sattolo's algorithm. Some more details on this are found here:
- https://en.wikipedia.org/wiki/Fisher–Yates_shuffle#Sattolo's_algorithm
- https://danluu.com/sattolo/
- https://rosettacode.org/wiki/Sattolo_cycle
Examples
import std.rand (Shuffle)
let a = [10, 20]
Shuffle.new.sort(a)
a # => [20, 10]