How can I get a random number in Kotlin?

后端 未结 22 1512
一个人的身影
一个人的身影 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:44

    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()
    
    0 讨论(0)
  • 2020-12-12 15:47

    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())
                    }
            )
        }
    
    0 讨论(0)
  • 2020-12-12 15:48

    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.

    0 讨论(0)
  • 2020-12-12 15:48

    to be super duper ))

     fun rnd_int(min: Int, max: Int): Int {
            var max = max
            max -= min
            return (Math.random() * ++max).toInt() + min
        }
    
    0 讨论(0)
  • 2020-12-12 15:50

    Another way of implementing s1m0nw1's answer would be to access it through a variable. Not that its any more efficient but it saves you from having to type ().

    val ClosedRange<Int>.random: Int
        get() = Random().nextInt((endInclusive + 1) - start) +  start 
    

    And now it can be accessed as such

    (1..10).random
    
    0 讨论(0)
  • 2020-12-12 15:51

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

    val randomNumber = (0..10).random()
    
    0 讨论(0)
提交回复
热议问题