How can I get a random number in Kotlin?











up vote
68
down vote

favorite
14












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



Any suggestion?










share|improve this question




























    up vote
    68
    down vote

    favorite
    14












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



    Any suggestion?










    share|improve this question


























      up vote
      68
      down vote

      favorite
      14









      up vote
      68
      down vote

      favorite
      14






      14





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



      Any suggestion?










      share|improve this question















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



      Any suggestion?







      java random jvm kotlin






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 10 at 12:12









      s1m0nw1

      24.7k63899




      24.7k63899










      asked Aug 15 '17 at 0:49









      Yago Azedias

      8052823




      8052823
























          16 Answers
          16






          active

          oldest

          votes

















          up vote
          207
          down vote



          accepted










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



          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 do the following (source):



          Random.nextInt(0, 10)


          The extension function can hereby look like the following on all platforms:



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


          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.






          share|improve this answer























          • I assume this also uses Java's java.util.Random?
            – Simon Forsberg
            Mar 21 at 21:09










          • @SimonForsberg Indeed. I added another answer which doesn't make use of it: stackoverflow.com/a/49507413/8073652
            – s1m0nw1
            Mar 27 at 8:02


















          up vote
          36
          down vote













          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
          }





          share|improve this answer

















          • 1




            If you want to get a couple of ranged random Ints, you can use Random#int(size,from,to) instead in java-8.
            – holi-java
            Aug 15 '17 at 8:52








          • 3




            This solution doesn't work on Javascript / Native Kotlin. Perhaps it could be cool to make a more generic method to do this. :)
            – Valentin Michalak
            Jan 2 at 16:39










          • @ValentinMichalak you can try this one: stackoverflow.com/a/49507413/8073652
            – s1m0nw1
            Mar 28 at 12:40


















          up vote
          23
          down vote













          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






          share|improve this answer





















          • this one is useful for kotlin-native
            – user3471194
            Oct 28 at 23:58


















          up vote
          10
          down vote













          You can create an extension function similar to java.util.Random.nextInt(int) but one that takes an IntRange instead of an Int for its bound:



          fun Random.nextInt(range: IntRange): Int {
          return range.start + nextInt(range.last - range.start)
          }


          You can now use this with any Random instance:



          val random = Random()
          println(random.nextInt(5..9)) // prints 5, 6, 7, or 8


          If you don't want to have to manage your own Random instance then you can define a convenience method using, for example, ThreadLocalRandom.current():



          fun rand(range: IntRange): Int {
          return ThreadLocalRandom.current().nextInt(range)
          }


          Now you can get a random integer as you would in Ruby without having to first declare a Random instance yourself:



          rand(5..9) // returns 5, 6, 7, or 8





          share|improve this answer




























            up vote
            8
            down vote













            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 do the following (source):



            fun ClosedRange<Char>.random(): Char = Random.nextInt(start.toInt(), endInclusive.toInt() + 1).toChar()





            share|improve this answer






























              up vote
              6
              down vote













              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())
              }
              )
              }





              share|improve this answer






























                up vote
                5
                down vote













                Examples random in the range [1, 10]



                val random1 = (0..10).shuffled().last()


                or utilizing Java Random



                val random2 = Random().nextInt(10) + 1





                share|improve this answer

















                • 1




                  Your first answer I like the most. It's a perfect one-liner that does not requre to write any extension functions
                  – Alex Semeniuk
                  Jul 24 at 15:37


















                up vote
                4
                down vote













                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()


                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 do the following (source):



                Random.nextInt(0, 10)


                The extension function can hereby be simplified to the following on all platforms:



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





                share|improve this answer






























                  up vote
                  3
                  down vote













                  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 ().



                  var ClosedRange<Int>.random: Int
                  get() { return Random().nextInt((endInclusive + 1) - start) + start }
                  private set(value) {}


                  And now it can be accessed as such



                  (1..10).random





                  share|improve this answer




























                    up vote
                    2
                    down vote













                    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(e + 1 - s) + s


                    Usage:



                    rand(1, 3) // returns either 1, 2 or 3





                    share|improve this answer






























                      up vote
                      1
                      down vote













                      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).






                      share|improve this answer




























                        up vote
                        1
                        down vote













                        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]





                        share|improve this answer




























                          up vote
                          1
                          down vote













                          If the numbers you want to choose from are not consecutive, you can define your own extension function on List:



                          fun List<*>.randomElement() 
                          = if (this.isEmpty()) null else this[Random().nextInt(this.size)]


                          Usage:



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


                          Returns one of the numbers which are in the list.






                          share|improve this answer






























                            up vote
                            1
                            down vote













                            Kotlin standard lib doesn't provide Random Number Generator API. If you aren't in a multiplatform project, it's better to use the platform api (all the others answers of the question talk about this solution).



                            But if you are in a multiplatform context, the best solution is to implement random by yourself in pure kotlin for share the same random number generator between platforms. It's more simple for dev and testing.



                            To answer to this problem in my personal project, i implement a pure Kotlin Linear Congruential Generator. LCG is the algorithm used by java.util.Random. Follow this link if you want to use it :
                            https://gist.github.com/11e5ddb567786af0ed1ae4d7f57441d4



                            My implementation purpose nextInt(range: IntRange) for you ;).



                            Take care about my purpose, LCG is good for most of the use cases (simulation, games, etc...) but is not suitable for cryptographically usage because of the predictability of this method.






                            share|improve this answer























                            • I'd rather rely on platform specific code than make my own random algorithm. This reminds me a bit about the code for java.util.Random, but it doesn't completely match.
                              – Simon Forsberg
                              Mar 21 at 21:23


















                            up vote
                            0
                            down vote













                            In Kotlin 1.3 you can do it like



                            val number = Random.nextInt(limit)





                            share|improve this answer




























                              up vote
                              -1
                              down vote













                              to be super duper ))



                               fun rnd_int(min: Int, max: Int): Int {
                              var max = max
                              max -= min
                              return (Math.random() * ++max).toInt() + min
                              }





                              share|improve this answer





















                                Your Answer






                                StackExchange.ifUsing("editor", function () {
                                StackExchange.using("externalEditor", function () {
                                StackExchange.using("snippets", function () {
                                StackExchange.snippets.init();
                                });
                                });
                                }, "code-snippets");

                                StackExchange.ready(function() {
                                var channelOptions = {
                                tags: "".split(" "),
                                id: "1"
                                };
                                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                StackExchange.using("externalEditor", function() {
                                // Have to fire editor after snippets, if snippets enabled
                                if (StackExchange.settings.snippets.snippetsEnabled) {
                                StackExchange.using("snippets", function() {
                                createEditor();
                                });
                                }
                                else {
                                createEditor();
                                }
                                });

                                function createEditor() {
                                StackExchange.prepareEditor({
                                heartbeatType: 'answer',
                                convertImagesToLinks: true,
                                noModals: true,
                                showLowRepImageUploadWarning: true,
                                reputationToPostImages: 10,
                                bindNavPrevention: true,
                                postfix: "",
                                imageUploader: {
                                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                allowUrls: true
                                },
                                onDemand: true,
                                discardSelector: ".discard-answer"
                                ,immediatelyShowMarkdownHelp:true
                                });


                                }
                                });














                                draft saved

                                draft discarded


















                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45685026%2fhow-can-i-get-a-random-number-in-kotlin%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown

























                                16 Answers
                                16






                                active

                                oldest

                                votes








                                16 Answers
                                16






                                active

                                oldest

                                votes









                                active

                                oldest

                                votes






                                active

                                oldest

                                votes








                                up vote
                                207
                                down vote



                                accepted










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



                                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 do the following (source):



                                Random.nextInt(0, 10)


                                The extension function can hereby look like the following on all platforms:



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


                                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.






                                share|improve this answer























                                • I assume this also uses Java's java.util.Random?
                                  – Simon Forsberg
                                  Mar 21 at 21:09










                                • @SimonForsberg Indeed. I added another answer which doesn't make use of it: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 27 at 8:02















                                up vote
                                207
                                down vote



                                accepted










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



                                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 do the following (source):



                                Random.nextInt(0, 10)


                                The extension function can hereby look like the following on all platforms:



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


                                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.






                                share|improve this answer























                                • I assume this also uses Java's java.util.Random?
                                  – Simon Forsberg
                                  Mar 21 at 21:09










                                • @SimonForsberg Indeed. I added another answer which doesn't make use of it: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 27 at 8:02













                                up vote
                                207
                                down vote



                                accepted







                                up vote
                                207
                                down vote



                                accepted






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



                                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 do the following (source):



                                Random.nextInt(0, 10)


                                The extension function can hereby look like the following on all platforms:



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


                                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.






                                share|improve this answer














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



                                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 do the following (source):



                                Random.nextInt(0, 10)


                                The extension function can hereby look like the following on all platforms:



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


                                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.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Dec 7 at 14:49

























                                answered Aug 15 '17 at 6:44









                                s1m0nw1

                                24.7k63899




                                24.7k63899












                                • I assume this also uses Java's java.util.Random?
                                  – Simon Forsberg
                                  Mar 21 at 21:09










                                • @SimonForsberg Indeed. I added another answer which doesn't make use of it: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 27 at 8:02


















                                • I assume this also uses Java's java.util.Random?
                                  – Simon Forsberg
                                  Mar 21 at 21:09










                                • @SimonForsberg Indeed. I added another answer which doesn't make use of it: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 27 at 8:02
















                                I assume this also uses Java's java.util.Random?
                                – Simon Forsberg
                                Mar 21 at 21:09




                                I assume this also uses Java's java.util.Random?
                                – Simon Forsberg
                                Mar 21 at 21:09












                                @SimonForsberg Indeed. I added another answer which doesn't make use of it: stackoverflow.com/a/49507413/8073652
                                – s1m0nw1
                                Mar 27 at 8:02




                                @SimonForsberg Indeed. I added another answer which doesn't make use of it: stackoverflow.com/a/49507413/8073652
                                – s1m0nw1
                                Mar 27 at 8:02












                                up vote
                                36
                                down vote













                                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
                                }





                                share|improve this answer

















                                • 1




                                  If you want to get a couple of ranged random Ints, you can use Random#int(size,from,to) instead in java-8.
                                  – holi-java
                                  Aug 15 '17 at 8:52








                                • 3




                                  This solution doesn't work on Javascript / Native Kotlin. Perhaps it could be cool to make a more generic method to do this. :)
                                  – Valentin Michalak
                                  Jan 2 at 16:39










                                • @ValentinMichalak you can try this one: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 28 at 12:40















                                up vote
                                36
                                down vote













                                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
                                }





                                share|improve this answer

















                                • 1




                                  If you want to get a couple of ranged random Ints, you can use Random#int(size,from,to) instead in java-8.
                                  – holi-java
                                  Aug 15 '17 at 8:52








                                • 3




                                  This solution doesn't work on Javascript / Native Kotlin. Perhaps it could be cool to make a more generic method to do this. :)
                                  – Valentin Michalak
                                  Jan 2 at 16:39










                                • @ValentinMichalak you can try this one: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 28 at 12:40













                                up vote
                                36
                                down vote










                                up vote
                                36
                                down vote









                                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
                                }





                                share|improve this answer












                                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
                                }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Aug 15 '17 at 1:07









                                Magnus

                                5,1031635




                                5,1031635








                                • 1




                                  If you want to get a couple of ranged random Ints, you can use Random#int(size,from,to) instead in java-8.
                                  – holi-java
                                  Aug 15 '17 at 8:52








                                • 3




                                  This solution doesn't work on Javascript / Native Kotlin. Perhaps it could be cool to make a more generic method to do this. :)
                                  – Valentin Michalak
                                  Jan 2 at 16:39










                                • @ValentinMichalak you can try this one: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 28 at 12:40














                                • 1




                                  If you want to get a couple of ranged random Ints, you can use Random#int(size,from,to) instead in java-8.
                                  – holi-java
                                  Aug 15 '17 at 8:52








                                • 3




                                  This solution doesn't work on Javascript / Native Kotlin. Perhaps it could be cool to make a more generic method to do this. :)
                                  – Valentin Michalak
                                  Jan 2 at 16:39










                                • @ValentinMichalak you can try this one: stackoverflow.com/a/49507413/8073652
                                  – s1m0nw1
                                  Mar 28 at 12:40








                                1




                                1




                                If you want to get a couple of ranged random Ints, you can use Random#int(size,from,to) instead in java-8.
                                – holi-java
                                Aug 15 '17 at 8:52






                                If you want to get a couple of ranged random Ints, you can use Random#int(size,from,to) instead in java-8.
                                – holi-java
                                Aug 15 '17 at 8:52






                                3




                                3




                                This solution doesn't work on Javascript / Native Kotlin. Perhaps it could be cool to make a more generic method to do this. :)
                                – Valentin Michalak
                                Jan 2 at 16:39




                                This solution doesn't work on Javascript / Native Kotlin. Perhaps it could be cool to make a more generic method to do this. :)
                                – Valentin Michalak
                                Jan 2 at 16:39












                                @ValentinMichalak you can try this one: stackoverflow.com/a/49507413/8073652
                                – s1m0nw1
                                Mar 28 at 12:40




                                @ValentinMichalak you can try this one: stackoverflow.com/a/49507413/8073652
                                – s1m0nw1
                                Mar 28 at 12:40










                                up vote
                                23
                                down vote













                                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






                                share|improve this answer





















                                • this one is useful for kotlin-native
                                  – user3471194
                                  Oct 28 at 23:58















                                up vote
                                23
                                down vote













                                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






                                share|improve this answer





















                                • this one is useful for kotlin-native
                                  – user3471194
                                  Oct 28 at 23:58













                                up vote
                                23
                                down vote










                                up vote
                                23
                                down vote









                                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






                                share|improve this answer












                                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







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Feb 15 at 22:59









                                mutexkid

                                789811




                                789811












                                • this one is useful for kotlin-native
                                  – user3471194
                                  Oct 28 at 23:58


















                                • this one is useful for kotlin-native
                                  – user3471194
                                  Oct 28 at 23:58
















                                this one is useful for kotlin-native
                                – user3471194
                                Oct 28 at 23:58




                                this one is useful for kotlin-native
                                – user3471194
                                Oct 28 at 23:58










                                up vote
                                10
                                down vote













                                You can create an extension function similar to java.util.Random.nextInt(int) but one that takes an IntRange instead of an Int for its bound:



                                fun Random.nextInt(range: IntRange): Int {
                                return range.start + nextInt(range.last - range.start)
                                }


                                You can now use this with any Random instance:



                                val random = Random()
                                println(random.nextInt(5..9)) // prints 5, 6, 7, or 8


                                If you don't want to have to manage your own Random instance then you can define a convenience method using, for example, ThreadLocalRandom.current():



                                fun rand(range: IntRange): Int {
                                return ThreadLocalRandom.current().nextInt(range)
                                }


                                Now you can get a random integer as you would in Ruby without having to first declare a Random instance yourself:



                                rand(5..9) // returns 5, 6, 7, or 8





                                share|improve this answer

























                                  up vote
                                  10
                                  down vote













                                  You can create an extension function similar to java.util.Random.nextInt(int) but one that takes an IntRange instead of an Int for its bound:



                                  fun Random.nextInt(range: IntRange): Int {
                                  return range.start + nextInt(range.last - range.start)
                                  }


                                  You can now use this with any Random instance:



                                  val random = Random()
                                  println(random.nextInt(5..9)) // prints 5, 6, 7, or 8


                                  If you don't want to have to manage your own Random instance then you can define a convenience method using, for example, ThreadLocalRandom.current():



                                  fun rand(range: IntRange): Int {
                                  return ThreadLocalRandom.current().nextInt(range)
                                  }


                                  Now you can get a random integer as you would in Ruby without having to first declare a Random instance yourself:



                                  rand(5..9) // returns 5, 6, 7, or 8





                                  share|improve this answer























                                    up vote
                                    10
                                    down vote










                                    up vote
                                    10
                                    down vote









                                    You can create an extension function similar to java.util.Random.nextInt(int) but one that takes an IntRange instead of an Int for its bound:



                                    fun Random.nextInt(range: IntRange): Int {
                                    return range.start + nextInt(range.last - range.start)
                                    }


                                    You can now use this with any Random instance:



                                    val random = Random()
                                    println(random.nextInt(5..9)) // prints 5, 6, 7, or 8


                                    If you don't want to have to manage your own Random instance then you can define a convenience method using, for example, ThreadLocalRandom.current():



                                    fun rand(range: IntRange): Int {
                                    return ThreadLocalRandom.current().nextInt(range)
                                    }


                                    Now you can get a random integer as you would in Ruby without having to first declare a Random instance yourself:



                                    rand(5..9) // returns 5, 6, 7, or 8





                                    share|improve this answer












                                    You can create an extension function similar to java.util.Random.nextInt(int) but one that takes an IntRange instead of an Int for its bound:



                                    fun Random.nextInt(range: IntRange): Int {
                                    return range.start + nextInt(range.last - range.start)
                                    }


                                    You can now use this with any Random instance:



                                    val random = Random()
                                    println(random.nextInt(5..9)) // prints 5, 6, 7, or 8


                                    If you don't want to have to manage your own Random instance then you can define a convenience method using, for example, ThreadLocalRandom.current():



                                    fun rand(range: IntRange): Int {
                                    return ThreadLocalRandom.current().nextInt(range)
                                    }


                                    Now you can get a random integer as you would in Ruby without having to first declare a Random instance yourself:



                                    rand(5..9) // returns 5, 6, 7, or 8






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Aug 19 '17 at 23:21









                                    mfulton26

                                    14k42651




                                    14k42651






















                                        up vote
                                        8
                                        down vote













                                        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 do the following (source):



                                        fun ClosedRange<Char>.random(): Char = Random.nextInt(start.toInt(), endInclusive.toInt() + 1).toChar()





                                        share|improve this answer



























                                          up vote
                                          8
                                          down vote













                                          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 do the following (source):



                                          fun ClosedRange<Char>.random(): Char = Random.nextInt(start.toInt(), endInclusive.toInt() + 1).toChar()





                                          share|improve this answer

























                                            up vote
                                            8
                                            down vote










                                            up vote
                                            8
                                            down vote









                                            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 do the following (source):



                                            fun ClosedRange<Char>.random(): Char = Random.nextInt(start.toInt(), endInclusive.toInt() + 1).toChar()





                                            share|improve this answer














                                            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 do the following (source):



                                            fun ClosedRange<Char>.random(): Char = Random.nextInt(start.toInt(), endInclusive.toInt() + 1).toChar()






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Nov 9 at 7:45

























                                            answered Dec 18 '17 at 7:23









                                            s1m0nw1

                                            24.7k63899




                                            24.7k63899






















                                                up vote
                                                6
                                                down vote













                                                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())
                                                }
                                                )
                                                }





                                                share|improve this answer



























                                                  up vote
                                                  6
                                                  down vote













                                                  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())
                                                  }
                                                  )
                                                  }





                                                  share|improve this answer

























                                                    up vote
                                                    6
                                                    down vote










                                                    up vote
                                                    6
                                                    down vote









                                                    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())
                                                    }
                                                    )
                                                    }





                                                    share|improve this answer














                                                    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())
                                                    }
                                                    )
                                                    }






                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Jan 10 at 4:31









                                                    s1m0nw1

                                                    24.7k63899




                                                    24.7k63899










                                                    answered Oct 5 '17 at 13:28









                                                    Steven Spungin

                                                    6,48322230




                                                    6,48322230






















                                                        up vote
                                                        5
                                                        down vote













                                                        Examples random in the range [1, 10]



                                                        val random1 = (0..10).shuffled().last()


                                                        or utilizing Java Random



                                                        val random2 = Random().nextInt(10) + 1





                                                        share|improve this answer

















                                                        • 1




                                                          Your first answer I like the most. It's a perfect one-liner that does not requre to write any extension functions
                                                          – Alex Semeniuk
                                                          Jul 24 at 15:37















                                                        up vote
                                                        5
                                                        down vote













                                                        Examples random in the range [1, 10]



                                                        val random1 = (0..10).shuffled().last()


                                                        or utilizing Java Random



                                                        val random2 = Random().nextInt(10) + 1





                                                        share|improve this answer

















                                                        • 1




                                                          Your first answer I like the most. It's a perfect one-liner that does not requre to write any extension functions
                                                          – Alex Semeniuk
                                                          Jul 24 at 15:37













                                                        up vote
                                                        5
                                                        down vote










                                                        up vote
                                                        5
                                                        down vote









                                                        Examples random in the range [1, 10]



                                                        val random1 = (0..10).shuffled().last()


                                                        or utilizing Java Random



                                                        val random2 = Random().nextInt(10) + 1





                                                        share|improve this answer












                                                        Examples random in the range [1, 10]



                                                        val random1 = (0..10).shuffled().last()


                                                        or utilizing Java Random



                                                        val random2 = Random().nextInt(10) + 1






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jul 1 at 15:26









                                                        Andrey

                                                        17.7k79077




                                                        17.7k79077








                                                        • 1




                                                          Your first answer I like the most. It's a perfect one-liner that does not requre to write any extension functions
                                                          – Alex Semeniuk
                                                          Jul 24 at 15:37














                                                        • 1




                                                          Your first answer I like the most. It's a perfect one-liner that does not requre to write any extension functions
                                                          – Alex Semeniuk
                                                          Jul 24 at 15:37








                                                        1




                                                        1




                                                        Your first answer I like the most. It's a perfect one-liner that does not requre to write any extension functions
                                                        – Alex Semeniuk
                                                        Jul 24 at 15:37




                                                        Your first answer I like the most. It's a perfect one-liner that does not requre to write any extension functions
                                                        – Alex Semeniuk
                                                        Jul 24 at 15:37










                                                        up vote
                                                        4
                                                        down vote













                                                        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()


                                                        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 do the following (source):



                                                        Random.nextInt(0, 10)


                                                        The extension function can hereby be simplified to the following on all platforms:



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





                                                        share|improve this answer



























                                                          up vote
                                                          4
                                                          down vote













                                                          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()


                                                          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 do the following (source):



                                                          Random.nextInt(0, 10)


                                                          The extension function can hereby be simplified to the following on all platforms:



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





                                                          share|improve this answer

























                                                            up vote
                                                            4
                                                            down vote










                                                            up vote
                                                            4
                                                            down vote









                                                            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()


                                                            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 do the following (source):



                                                            Random.nextInt(0, 10)


                                                            The extension function can hereby be simplified to the following on all platforms:



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





                                                            share|improve this answer














                                                            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()


                                                            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 do the following (source):



                                                            Random.nextInt(0, 10)


                                                            The extension function can hereby be simplified to the following on all platforms:



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






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Nov 9 at 7:37

























                                                            answered Mar 27 at 8:01









                                                            s1m0nw1

                                                            24.7k63899




                                                            24.7k63899






















                                                                up vote
                                                                3
                                                                down vote













                                                                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 ().



                                                                var ClosedRange<Int>.random: Int
                                                                get() { return Random().nextInt((endInclusive + 1) - start) + start }
                                                                private set(value) {}


                                                                And now it can be accessed as such



                                                                (1..10).random





                                                                share|improve this answer

























                                                                  up vote
                                                                  3
                                                                  down vote













                                                                  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 ().



                                                                  var ClosedRange<Int>.random: Int
                                                                  get() { return Random().nextInt((endInclusive + 1) - start) + start }
                                                                  private set(value) {}


                                                                  And now it can be accessed as such



                                                                  (1..10).random





                                                                  share|improve this answer























                                                                    up vote
                                                                    3
                                                                    down vote










                                                                    up vote
                                                                    3
                                                                    down vote









                                                                    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 ().



                                                                    var ClosedRange<Int>.random: Int
                                                                    get() { return Random().nextInt((endInclusive + 1) - start) + start }
                                                                    private set(value) {}


                                                                    And now it can be accessed as such



                                                                    (1..10).random





                                                                    share|improve this answer












                                                                    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 ().



                                                                    var ClosedRange<Int>.random: Int
                                                                    get() { return Random().nextInt((endInclusive + 1) - start) + start }
                                                                    private set(value) {}


                                                                    And now it can be accessed as such



                                                                    (1..10).random






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Jul 19 at 2:14









                                                                    Quinn

                                                                    3628




                                                                    3628






















                                                                        up vote
                                                                        2
                                                                        down vote













                                                                        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(e + 1 - s) + s


                                                                        Usage:



                                                                        rand(1, 3) // returns either 1, 2 or 3





                                                                        share|improve this answer



























                                                                          up vote
                                                                          2
                                                                          down vote













                                                                          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(e + 1 - s) + s


                                                                          Usage:



                                                                          rand(1, 3) // returns either 1, 2 or 3





                                                                          share|improve this answer

























                                                                            up vote
                                                                            2
                                                                            down vote










                                                                            up vote
                                                                            2
                                                                            down vote









                                                                            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(e + 1 - s) + s


                                                                            Usage:



                                                                            rand(1, 3) // returns either 1, 2 or 3





                                                                            share|improve this answer














                                                                            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(e + 1 - s) + s


                                                                            Usage:



                                                                            rand(1, 3) // returns either 1, 2 or 3






                                                                            share|improve this answer














                                                                            share|improve this answer



                                                                            share|improve this answer








                                                                            edited Dec 19 '17 at 8:45

























                                                                            answered Dec 18 '17 at 16:09









                                                                            Willi Mentzel

                                                                            8,097114366




                                                                            8,097114366






















                                                                                up vote
                                                                                1
                                                                                down vote













                                                                                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).






                                                                                share|improve this answer

























                                                                                  up vote
                                                                                  1
                                                                                  down vote













                                                                                  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).






                                                                                  share|improve this answer























                                                                                    up vote
                                                                                    1
                                                                                    down vote










                                                                                    up vote
                                                                                    1
                                                                                    down vote









                                                                                    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).






                                                                                    share|improve this answer












                                                                                    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).







                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Aug 15 '17 at 1:02









                                                                                    Mibac

                                                                                    3,48522140




                                                                                    3,48522140






















                                                                                        up vote
                                                                                        1
                                                                                        down vote













                                                                                        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]





                                                                                        share|improve this answer

























                                                                                          up vote
                                                                                          1
                                                                                          down vote













                                                                                          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]





                                                                                          share|improve this answer























                                                                                            up vote
                                                                                            1
                                                                                            down vote










                                                                                            up vote
                                                                                            1
                                                                                            down vote









                                                                                            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]





                                                                                            share|improve this answer












                                                                                            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]






                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered Aug 15 '17 at 6:19









                                                                                            Mahdi AlKhalaf

                                                                                            164




                                                                                            164






















                                                                                                up vote
                                                                                                1
                                                                                                down vote













                                                                                                If the numbers you want to choose from are not consecutive, you can define your own extension function on List:



                                                                                                fun List<*>.randomElement() 
                                                                                                = if (this.isEmpty()) null else this[Random().nextInt(this.size)]


                                                                                                Usage:



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


                                                                                                Returns one of the numbers which are in the list.






                                                                                                share|improve this answer



























                                                                                                  up vote
                                                                                                  1
                                                                                                  down vote













                                                                                                  If the numbers you want to choose from are not consecutive, you can define your own extension function on List:



                                                                                                  fun List<*>.randomElement() 
                                                                                                  = if (this.isEmpty()) null else this[Random().nextInt(this.size)]


                                                                                                  Usage:



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


                                                                                                  Returns one of the numbers which are in the list.






                                                                                                  share|improve this answer

























                                                                                                    up vote
                                                                                                    1
                                                                                                    down vote










                                                                                                    up vote
                                                                                                    1
                                                                                                    down vote









                                                                                                    If the numbers you want to choose from are not consecutive, you can define your own extension function on List:



                                                                                                    fun List<*>.randomElement() 
                                                                                                    = if (this.isEmpty()) null else this[Random().nextInt(this.size)]


                                                                                                    Usage:



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


                                                                                                    Returns one of the numbers which are in the list.






                                                                                                    share|improve this answer














                                                                                                    If the numbers you want to choose from are not consecutive, you can define your own extension function on List:



                                                                                                    fun List<*>.randomElement() 
                                                                                                    = if (this.isEmpty()) null else this[Random().nextInt(this.size)]


                                                                                                    Usage:



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


                                                                                                    Returns one of the numbers which are in the list.







                                                                                                    share|improve this answer














                                                                                                    share|improve this answer



                                                                                                    share|improve this answer








                                                                                                    edited Dec 19 '17 at 8:53

























                                                                                                    answered Dec 18 '17 at 16:15









                                                                                                    Willi Mentzel

                                                                                                    8,097114366




                                                                                                    8,097114366






















                                                                                                        up vote
                                                                                                        1
                                                                                                        down vote













                                                                                                        Kotlin standard lib doesn't provide Random Number Generator API. If you aren't in a multiplatform project, it's better to use the platform api (all the others answers of the question talk about this solution).



                                                                                                        But if you are in a multiplatform context, the best solution is to implement random by yourself in pure kotlin for share the same random number generator between platforms. It's more simple for dev and testing.



                                                                                                        To answer to this problem in my personal project, i implement a pure Kotlin Linear Congruential Generator. LCG is the algorithm used by java.util.Random. Follow this link if you want to use it :
                                                                                                        https://gist.github.com/11e5ddb567786af0ed1ae4d7f57441d4



                                                                                                        My implementation purpose nextInt(range: IntRange) for you ;).



                                                                                                        Take care about my purpose, LCG is good for most of the use cases (simulation, games, etc...) but is not suitable for cryptographically usage because of the predictability of this method.






                                                                                                        share|improve this answer























                                                                                                        • I'd rather rely on platform specific code than make my own random algorithm. This reminds me a bit about the code for java.util.Random, but it doesn't completely match.
                                                                                                          – Simon Forsberg
                                                                                                          Mar 21 at 21:23















                                                                                                        up vote
                                                                                                        1
                                                                                                        down vote













                                                                                                        Kotlin standard lib doesn't provide Random Number Generator API. If you aren't in a multiplatform project, it's better to use the platform api (all the others answers of the question talk about this solution).



                                                                                                        But if you are in a multiplatform context, the best solution is to implement random by yourself in pure kotlin for share the same random number generator between platforms. It's more simple for dev and testing.



                                                                                                        To answer to this problem in my personal project, i implement a pure Kotlin Linear Congruential Generator. LCG is the algorithm used by java.util.Random. Follow this link if you want to use it :
                                                                                                        https://gist.github.com/11e5ddb567786af0ed1ae4d7f57441d4



                                                                                                        My implementation purpose nextInt(range: IntRange) for you ;).



                                                                                                        Take care about my purpose, LCG is good for most of the use cases (simulation, games, etc...) but is not suitable for cryptographically usage because of the predictability of this method.






                                                                                                        share|improve this answer























                                                                                                        • I'd rather rely on platform specific code than make my own random algorithm. This reminds me a bit about the code for java.util.Random, but it doesn't completely match.
                                                                                                          – Simon Forsberg
                                                                                                          Mar 21 at 21:23













                                                                                                        up vote
                                                                                                        1
                                                                                                        down vote










                                                                                                        up vote
                                                                                                        1
                                                                                                        down vote









                                                                                                        Kotlin standard lib doesn't provide Random Number Generator API. If you aren't in a multiplatform project, it's better to use the platform api (all the others answers of the question talk about this solution).



                                                                                                        But if you are in a multiplatform context, the best solution is to implement random by yourself in pure kotlin for share the same random number generator between platforms. It's more simple for dev and testing.



                                                                                                        To answer to this problem in my personal project, i implement a pure Kotlin Linear Congruential Generator. LCG is the algorithm used by java.util.Random. Follow this link if you want to use it :
                                                                                                        https://gist.github.com/11e5ddb567786af0ed1ae4d7f57441d4



                                                                                                        My implementation purpose nextInt(range: IntRange) for you ;).



                                                                                                        Take care about my purpose, LCG is good for most of the use cases (simulation, games, etc...) but is not suitable for cryptographically usage because of the predictability of this method.






                                                                                                        share|improve this answer














                                                                                                        Kotlin standard lib doesn't provide Random Number Generator API. If you aren't in a multiplatform project, it's better to use the platform api (all the others answers of the question talk about this solution).



                                                                                                        But if you are in a multiplatform context, the best solution is to implement random by yourself in pure kotlin for share the same random number generator between platforms. It's more simple for dev and testing.



                                                                                                        To answer to this problem in my personal project, i implement a pure Kotlin Linear Congruential Generator. LCG is the algorithm used by java.util.Random. Follow this link if you want to use it :
                                                                                                        https://gist.github.com/11e5ddb567786af0ed1ae4d7f57441d4



                                                                                                        My implementation purpose nextInt(range: IntRange) for you ;).



                                                                                                        Take care about my purpose, LCG is good for most of the use cases (simulation, games, etc...) but is not suitable for cryptographically usage because of the predictability of this method.







                                                                                                        share|improve this answer














                                                                                                        share|improve this answer



                                                                                                        share|improve this answer








                                                                                                        edited Jan 11 at 9:54

























                                                                                                        answered Jan 11 at 9:46









                                                                                                        Valentin Michalak

                                                                                                        1,168521




                                                                                                        1,168521












                                                                                                        • I'd rather rely on platform specific code than make my own random algorithm. This reminds me a bit about the code for java.util.Random, but it doesn't completely match.
                                                                                                          – Simon Forsberg
                                                                                                          Mar 21 at 21:23


















                                                                                                        • I'd rather rely on platform specific code than make my own random algorithm. This reminds me a bit about the code for java.util.Random, but it doesn't completely match.
                                                                                                          – Simon Forsberg
                                                                                                          Mar 21 at 21:23
















                                                                                                        I'd rather rely on platform specific code than make my own random algorithm. This reminds me a bit about the code for java.util.Random, but it doesn't completely match.
                                                                                                        – Simon Forsberg
                                                                                                        Mar 21 at 21:23




                                                                                                        I'd rather rely on platform specific code than make my own random algorithm. This reminds me a bit about the code for java.util.Random, but it doesn't completely match.
                                                                                                        – Simon Forsberg
                                                                                                        Mar 21 at 21:23










                                                                                                        up vote
                                                                                                        0
                                                                                                        down vote













                                                                                                        In Kotlin 1.3 you can do it like



                                                                                                        val number = Random.nextInt(limit)





                                                                                                        share|improve this answer

























                                                                                                          up vote
                                                                                                          0
                                                                                                          down vote













                                                                                                          In Kotlin 1.3 you can do it like



                                                                                                          val number = Random.nextInt(limit)





                                                                                                          share|improve this answer























                                                                                                            up vote
                                                                                                            0
                                                                                                            down vote










                                                                                                            up vote
                                                                                                            0
                                                                                                            down vote









                                                                                                            In Kotlin 1.3 you can do it like



                                                                                                            val number = Random.nextInt(limit)





                                                                                                            share|improve this answer












                                                                                                            In Kotlin 1.3 you can do it like



                                                                                                            val number = Random.nextInt(limit)






                                                                                                            share|improve this answer












                                                                                                            share|improve this answer



                                                                                                            share|improve this answer










                                                                                                            answered Sep 13 at 14:42









                                                                                                            deviant

                                                                                                            2,12722235




                                                                                                            2,12722235






















                                                                                                                up vote
                                                                                                                -1
                                                                                                                down vote













                                                                                                                to be super duper ))



                                                                                                                 fun rnd_int(min: Int, max: Int): Int {
                                                                                                                var max = max
                                                                                                                max -= min
                                                                                                                return (Math.random() * ++max).toInt() + min
                                                                                                                }





                                                                                                                share|improve this answer

























                                                                                                                  up vote
                                                                                                                  -1
                                                                                                                  down vote













                                                                                                                  to be super duper ))



                                                                                                                   fun rnd_int(min: Int, max: Int): Int {
                                                                                                                  var max = max
                                                                                                                  max -= min
                                                                                                                  return (Math.random() * ++max).toInt() + min
                                                                                                                  }





                                                                                                                  share|improve this answer























                                                                                                                    up vote
                                                                                                                    -1
                                                                                                                    down vote










                                                                                                                    up vote
                                                                                                                    -1
                                                                                                                    down vote









                                                                                                                    to be super duper ))



                                                                                                                     fun rnd_int(min: Int, max: Int): Int {
                                                                                                                    var max = max
                                                                                                                    max -= min
                                                                                                                    return (Math.random() * ++max).toInt() + min
                                                                                                                    }





                                                                                                                    share|improve this answer












                                                                                                                    to be super duper ))



                                                                                                                     fun rnd_int(min: Int, max: Int): Int {
                                                                                                                    var max = max
                                                                                                                    max -= min
                                                                                                                    return (Math.random() * ++max).toInt() + min
                                                                                                                    }






                                                                                                                    share|improve this answer












                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer










                                                                                                                    answered Nov 28 at 15:29









                                                                                                                    Deomin Dmitriy

                                                                                                                    11




                                                                                                                    11






























                                                                                                                        draft saved

                                                                                                                        draft discarded




















































                                                                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                                                                        But avoid



                                                                                                                        • Asking for help, clarification, or responding to other answers.

                                                                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                        To learn more, see our tips on writing great answers.





                                                                                                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                                                        Please pay close attention to the following guidance:


                                                                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                                                                        But avoid



                                                                                                                        • Asking for help, clarification, or responding to other answers.

                                                                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                        To learn more, see our tips on writing great answers.




                                                                                                                        draft saved


                                                                                                                        draft discarded














                                                                                                                        StackExchange.ready(
                                                                                                                        function () {
                                                                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45685026%2fhow-can-i-get-a-random-number-in-kotlin%23new-answer', 'question_page');
                                                                                                                        }
                                                                                                                        );

                                                                                                                        Post as a guest















                                                                                                                        Required, but never shown





















































                                                                                                                        Required, but never shown














                                                                                                                        Required, but never shown












                                                                                                                        Required, but never shown







                                                                                                                        Required, but never shown

































                                                                                                                        Required, but never shown














                                                                                                                        Required, but never shown












                                                                                                                        Required, but never shown







                                                                                                                        Required, but never shown







                                                                                                                        這個網誌中的熱門文章

                                                                                                                        Xamarin.form Move up view when keyboard appear

                                                                                                                        Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                                                                                                        JBPM : POST request for execute process go wrong