Introduce Sequence.shuffled

#KT-37751
This commit is contained in:
Ilya Gorbunov
2020-03-26 22:06:59 +03:00
parent f42d9eefa1
commit e58f1c8932
3 changed files with 91 additions and 2 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -8,6 +8,8 @@
package kotlin.sequences
import kotlin.random.Random
/**
* Given an [iterator] function constructs a [Sequence] that returns values through the [Iterator]
* provided by that function.
@@ -109,6 +111,36 @@ public fun <T, R> Sequence<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
return listT to listR
}
/**
* Returns a sequence that yields elements of this sequence randomly shuffled.
*
* Note that every iteration of the sequence returns elements in a different order.
*
* The operation is _intermediate_ and _stateful_.
*/
@SinceKotlin("1.4")
public fun <T> Sequence<T>.shuffled(): Sequence<T> = shuffled(Random)
/**
* Returns a sequence that yields elements of this sequence randomly shuffled
* using the specified [random] instance as the source of randomness.
*
* Note that every iteration of the sequence returns elements in a different order.
*
* The operation is _intermediate_ and _stateful_.
*/
@SinceKotlin("1.4")
public fun <T> Sequence<T>.shuffled(random: Random): Sequence<T> = sequence<T> {
val buffer = toMutableList()
while (buffer.isNotEmpty()) {
val j = random.nextInt(buffer.size)
val last = @OptIn(ExperimentalStdlibApi::class) buffer.removeLast()
val value = if (j < buffer.size) buffer.set(j, last) else last
yield(value)
}
}
/**
* A sequence that returns the values from the underlying [sequence] that either match or do not match
* the specified [predicate].