Many times, we need random numbers within certain range for various purposes in our programs. They can be generated using inbuilt random number generator functions. Lets check out how to do it in various programming languages.
Swift
1 2 3 4 5 6 7 8 9 |
//For swift version less than 4.2 //Use arc4random_uniform(n) //for a random integer between 0 and n-1 let diceRoll = Int(arc4random_uniform(6) + 1) //For swift versions higher than 4.2 let diceRoll = Int.random(in: 1…6) |
Kotlin
1 |
val rnds = (0..10).random() // generated random from 0 to 10 included |
JAVAScript
1 2 3 |
function randomIntFromInterval(min, max) { // min and max included return Math.floor(Math.random() * (max – min + 1) + min) } |
PHP
1 2 3 4 5 6 7 8 9 10 11 |
//Using rand() function. int rand ( void ) #OR int rand ( int $min , int $max ) //Using mt_rand() function int mt_rand ( void ) #OR int mt_rand ( int $min , int $max ) |
JAVA
1 |
Random().nextInt((max – min) + 1) + min |