Implement in-place shuffle for arrays

Minor: reorder shuffle/shuffled extensions more consistently

#KT-25651 Fixed
This commit is contained in:
Ilya Gorbunov
2020-03-26 21:52:11 +03:00
parent e58f1c8932
commit 15319eb88e
10 changed files with 487 additions and 43 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.
*/
@@ -10,6 +10,7 @@
package kotlin.collections
import kotlin.contracts.*
import kotlin.random.Random
internal object EmptyIterator : ListIterator<Nothing> {
override fun hasNext(): Boolean = false
@@ -266,6 +267,15 @@ public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : Collectio
@kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes T> Collection<T>.containsAll(elements: Collection<T>): Boolean = this.containsAll(elements)
/**
* Returns a new list with the elements of this list randomly shuffled
* using the specified [random] instance as the source of randomness.
*/
@SinceKotlin("1.3")
public fun <T> Iterable<T>.shuffled(random: Random): List<T> = toMutableList().apply { shuffle(random) }
internal fun <T> List<T>.optimizeReadOnlyList() = when (size) {
0 -> emptyList()
1 -> listOf(this[0])
@@ -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.
*/
@@ -225,14 +225,6 @@ private fun <T> MutableIterable<T>.filterInPlace(predicate: (T) -> Boolean, pred
}
/**
* Returns a new list with the elements of this list randomly shuffled
* using the specified [random] instance as the source of randomness.
*/
@SinceKotlin("1.3")
public fun <T> Iterable<T>.shuffled(random: Random): List<T> = toMutableList().apply { shuffle(random) }
/**
* Removes the element at the specified [index] from this list.
* In Kotlin one should use the [MutableList.removeAt] function instead.
@@ -307,19 +299,3 @@ private fun <T> MutableList<T>.filterInPlace(predicate: (T) -> Boolean, predicat
return false
}
}
/**
* Randomly shuffles elements in this mutable list using the specified [random] instance as the source of randomness.
*
* See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
*/
@SinceKotlin("1.3")
public fun <T> MutableList<T>.shuffle(random: Random): Unit {
for (i in lastIndex downTo 1) {
val j = random.nextInt(i + 1)
val copy = this[i]
this[i] = this[j]
this[j] = copy
}
}