How can I get a random number in Kotlin?

2019-01-30 17:32发布

A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n).

Any suggestion?

18条回答
一纸荒年 Trace。
2楼-- · 2019-01-30 17:50

Building off of @s1m0nw1 excellent answer I made the following changes.

  1. (0..n) implies inclusive in Kotlin
  2. (0 until n) implies exclusive in Kotlin
  3. Use a singleton object for the Random instance (optional)

Code:

private object RandomRangeSingleton : Random()

fun ClosedRange<Int>.random() = RandomRangeSingleton.nextInt((endInclusive + 1) - start) + start

Test Case:

fun testRandom() {
        Assert.assertTrue(
                (0..1000).all {
                    (0..5).contains((0..5).random())
                }
        )
        Assert.assertTrue(
                (0..1000).all {
                    (0..4).contains((0 until 5).random())
                }
        )
        Assert.assertFalse(
                (0..1000).all {
                    (0..4).contains((0..5).random())
                }
        )
    }
查看更多
孤傲高冷的网名
3楼-- · 2019-01-30 17:50

No need to use custom extension functions anymore. IntRange has a random() extension function out-of-the-box now.

val randomNumber = (0..10).random()
查看更多
够拽才男人
4楼-- · 2019-01-30 17:50

to be super duper ))

 fun rnd_int(min: Int, max: Int): Int {
        var max = max
        max -= min
        return (Math.random() * ++max).toInt() + min
    }
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-30 17:54

If the numbers you want to choose from are not consecutive, you can use random().

Usage:

val list = listOf(3, 1, 4, 5)
val number = list.random()

Returns one of the numbers which are in the list.

查看更多
够拽才男人
6楼-- · 2019-01-30 17:57

To get a random Int number in Kotlin use the following method:

import java.util.concurrent.ThreadLocalRandom

fun randomInt(rangeFirstNum:Int, rangeLastNum:Int) {
    val randomInteger = ThreadLocalRandom.current().nextInt(rangeFirstNum,rangeLastNum)
    println(randomInteger)
}
fun main() {    
    randomInt(1,10)
}


// Result – random Int numbers from 1 to 9

Hope this helps.

查看更多
Anthone
7楼-- · 2019-01-30 18:00

Kotlin >= 1.3, multiplatform support for Random

As of 1.3, the standard library provided multi-platform support for randoms, see this answer.

Kotlin < 1.3 on JavaScript

If you are working with Kotlin JavaScript and don't have access to java.util.Random, the following will work:

fun IntRange.random() = (Math.random() * ((endInclusive + 1) - start) + start).toInt()

Used like this:

// will return an `Int` between 0 and 10 (incl.)
(0..10).random()
查看更多
登录 后发表回答