How can i generate Random numbers in Kotlin

Published September 02, 2022

Kotlin we have different ways to generate Random numbers. 

  • Using Random class
  • Using random() method
  • Using shuffled() method

 

Generate Random numbers using Random class

In Kotlin Random is an abstract class which will used to generates random numbers. To work with Random class we need to import Kotlin.random.Random package

Below example, we will generate a list of random values with in the limit (0-25)

package com.example.kotlinexamples

import kotlin.random.Random

fun main(args: Array<String>) {


    val myRandomValues = List(5) { Random.nextInt(0, 25) }

    // Prints a new sequence every time
    println(myRandomValues)

}

 

Output:

[21, 13, 1, 12, 5]

 

Generate Random numbers using Random() method

fun main(args: Array<String>) {

    // It generates a random number between 0 to 20
    println((0..20).random())

}

 

Output:

14 (You may get different random number while executing the above code )

 

Using shuffled() method

Kotlin provided other method to generate randome numbers called shuffle

fun main(args: Array<String>) {

    val random1 = (0..50).shuffled().last()
    println(random1)

}

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

262 Views