Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 396 Vote(s) - 3.51 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I get a random number in Kotlin?

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

Any suggestion?
Reply

#2
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`][1]. You'll need to create an instance of it and then call `random.nextInt(n)`.


[1]:

[To see links please register here]

Reply

#3
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
}
Reply

#4
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]

Reply

#5
Building off of [@s1m0nw1][1] 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())
}
)
}


[1]:

[To see links please register here]

Reply

#6
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][1]. LCG is the algorithm used by `java.util.Random`. Follow this link if you want to use it :

[To see links please register here]


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.


[1]:

[To see links please register here]

Reply

#7
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
Reply

#8
Examples random in the range [1, 10]

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

or utilizing Java Random

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

#9

to be super duper ))

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

#10
If the numbers you want to choose from are not consecutive, you can use [`random()`][1].

Usage:

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

Returns one of the numbers which are in the list.


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through