How can I get a random number in Kotlin?

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

    Possible Variation to my other answer for random chars

    In order to get random Chars, you can define an extension function like this

    fun ClosedRange<Char>.random(): Char = 
           (Random().nextInt(endInclusive.toInt() + 1 - start.toInt()) + start.toInt()).toChar()
    
    // will return a `Char` between A and Z (incl.)
    ('A'..'Z').random()
    

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

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

    Kotlin >= 1.3 multiplatform support for Random

    As of 1.3, Kotlin comes with its own multiplatform Random generator. It is described in this KEEP. You can now directly use the extension as part of the Kotlin standard library without defining it:

    ('a'..'b').random()
    
    0 讨论(0)
  • 2020-12-12 15:53

    There is no standard method that does this but you can easily create your own using either Math.random() or the class java.util.Random. Here is an example using the Math.random() method:

    fun random(n: Int) = (Math.random() * n).toInt()
    fun random(from: Int, to: Int) = (Math.random() * (to - from) + from).toInt()
    fun random(pair: Pair<Int, Int>) = random(pair.first, pair.second)
    
    fun main(args: Array<String>) {
        val n = 10
    
        val rand1 = random(n)
        val rand2 = random(5, n)
        val rand3 = random(5 to n)
    
        println(List(10) { random(n) })
        println(List(10) { random(5 to n) })
    }
    

    This is a sample output:

    [9, 8, 1, 7, 5, 6, 9, 8, 1, 9]
    [5, 8, 9, 7, 6, 6, 8, 6, 7, 9]
    
    0 讨论(0)
  • 2020-12-12 15:54

    Generate a random integer between from(inclusive) and to(exclusive)

    import java.util.Random
    
    val random = Random()
    
    fun rand(from: Int, to: Int) : Int {
        return random.nextInt(to - from) + from
    }
    
    0 讨论(0)
  • 2020-12-12 15:54

    In Kotlin SDK >=1.3 you can do it like

    import kotlin.random.Random
    
    val number = Random.nextInt(limit)
    
    0 讨论(0)
  • 2020-12-12 15:54

    Full source code. Can control whether duplicates are allowed.

    import kotlin.math.min
    
    abstract class Random {
    
        companion object {
            fun string(length: Int, isUnique: Boolean = false): String {
                if (0 == length) return ""
                val alphabet: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9') // Add your set here.
    
                if (isUnique) {
                    val limit = min(length, alphabet.count())
                    val set = mutableSetOf<Char>()
                    do { set.add(alphabet.random()) } while (set.count() != limit)
                    return set.joinToString("")
                }
                return List(length) { alphabet.random() }.joinToString("")
            }
    
            fun alphabet(length: Int, isUnique: Boolean = false): String {
                if (0 == length) return ""
                val alphabet = ('A'..'Z')
                if (isUnique) {
                    val limit = min(length, alphabet.count())
                    val set = mutableSetOf<Char>()
                    do { set.add(alphabet.random()) } while (set.count() != limit)
                    return set.joinToString("")
                }
    
                return List(length) { alphabet.random() }.joinToString("")
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-12 15:58

    Using a top-level function, you can achieve exactly the same call syntax as in Ruby (as you wish):

    fun rand(s: Int, e: Int) = Random.nextInt(s, e + 1)
    

    Usage:

    rand(1, 3) // returns either 1, 2 or 3
    
    0 讨论(0)
提交回复
热议问题