Extension random() to select random element from a collection

Fixes #KT-15539
This commit is contained in:
Ilya Gorbunov
2018-08-24 06:12:50 +03:00
parent b0bcd78e38
commit ea2c33a532
20 changed files with 652 additions and 3 deletions
@@ -10,6 +10,8 @@ import kotlin.test.*
import test.collections.behaviors.*
import test.comparisons.STRING_CASE_INSENSITIVE_ORDER
import kotlin.comparisons.*
import kotlin.math.sin
import kotlin.random.Random
class CollectionTest {
@@ -620,6 +622,31 @@ class CollectionTest {
assertFails { arrayListOf<Int>().last() }
}
@Test fun random() {
val list = List(100) { it }
val set = list.toSet()
listOf(list, set).forEach { collection: Collection<Int> ->
val tosses = List(10) { collection.random() }
assertTrue(tosses.distinct().size > 1, "Should be some distinct elements in $tosses")
val seed = Random.nextInt()
val random1 = Random(seed)
val random2 = Random(seed)
val tosses1 = List(10) { collection.random(random1) }
val tosses2 = List(10) { collection.random(random2) }
assertEquals(tosses1, tosses2)
}
listOf("x").let { singletonList ->
val tosses = List(10) { singletonList.random() }
assertEquals(singletonList, tosses.distinct())
}
assertFailsWith<NoSuchElementException> { emptyList<Any>().random() }
}
@Test fun subscript() {
val list = arrayListOf("foo", "bar")
assertEquals("foo", list[0])