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.
*/
@@ -457,4 +457,57 @@ object Ordering : TemplateGroupBase() {
}
}
val f_shuffle = fn("shuffle()") {
include(InvariantArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.4")
returns("Unit")
doc {
"""
Randomly shuffles elements in this ${f.collection} in-place.
"""
}
body {
"shuffle(Random)"
}
}
val f_shuffleRandom = fn("shuffle(random: Random)") {
include(Lists, InvariantArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.4")
returns("Unit")
doc {
"""
Randomly shuffles elements in this ${f.collection} in-place using the specified [random] instance as the source of randomness.
See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
"""
}
specialFor(Lists) {
since("1.3")
receiver("MutableList<T>")
}
body {
"""
for (i in lastIndex downTo 1) {
val j = random.nextInt(i + 1)
val copy = this[i]
this[i] = this[j]
this[j] = copy
}
"""
}
specialFor(Lists) {
body {
"""
for (i in lastIndex downTo 1) {
val j = random.nextInt(i + 1)
this[j] = this.set(i, this[j])
}
"""
}
}
}
}