How can I get a random number in Kotlin?

后端 未结 22 1514
一个人的身影
一个人的身影 2020-12-12 15:02

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

Any suggestion?

相关标签:
22条回答
  • 2020-12-12 15:58

    Below in Kotlin worked well for me:

    (fromNumber.rangeTo(toNumber)).random()
    

    Range of the numbers starts with variable fromNumber and ends with variable toNumber. fromNumber and toNumber will also be included in the random numbers generated out of this.

    0 讨论(0)
  • 2020-12-12 16:00

    My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()

    TL;DR Kotlin >= 1.3, one Random for all platforms

    As of 1.3, Kotlin comes with its own multi-platform Random generator. It is described in this KEEP. The extension described below is now part of the Kotlin standard library, simply use it like this:

    val rnds = (0..10).random() // generated random from 1 to 9 included
    

    Kotlin < 1.3

    Before 1.3, on the JVM we use Random or even ThreadLocalRandom if we're on JDK > 1.6.

    fun IntRange.random() = 
           Random().nextInt((endInclusive + 1) - start) + start
    

    Used like this:

    // will return an `Int` between 0 and 10 (incl.)
    (0..10).random()
    

    If you wanted the function only to return 1, 2, ..., 9 (10 not included), use a range constructed with until:

    (0 until 10).random()
    

    If you're working with JDK > 1.6, use ThreadLocalRandom.current() instead of Random().

    KotlinJs and other variations

    For kotlinjs and other use cases which don't allow the usage of java.util.Random, see this alternative.

    Also, see this answer for variations of my suggestion. It also includes an extension function for random Chars.

    0 讨论(0)
  • 2020-12-12 16:00

    As of kotlin 1.2, you could write:

    (1..3).shuffled().last()

    Just be aware it's big O(n), but for a small list (especially of unique values) it's alright :D

    0 讨论(0)
  • 2020-12-12 16:01

    Whenever there is a situation where you want to generate key or mac address which is hexadecimal number having digits based on user demand, and that too using android and kotlin, then you my below code helps you:

    private fun getRandomHexString(random: SecureRandom, numOfCharsToBePresentInTheHexString: Int): String {
        val sb = StringBuilder()
        while (sb.length < numOfCharsToBePresentInTheHexString) {
            val randomNumber = random.nextInt()
            val number = String.format("%08X", randomNumber)
            sb.append(number)
        }
        return sb.toString()
    } 
    
    0 讨论(0)
  • 2020-12-12 16:02

    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.

    0 讨论(0)
  • 2020-12-12 16:03

    First, you need a RNG. In Kotlin you currently need to use the platform specific ones (there isn't a Kotlin built in one). For the JVM it's java.util.Random. You'll need to create an instance of it and then call random.nextInt(n).

    0 讨论(0)
提交回复
热议问题