Select random number but exclude a particular value

Viewed 248

In Kotlin I would like to select a random value between 0 and 10 but at the same time specify a value that should not be selected. For example if I specify not to select the number 5, it will skip this value and choose only from the other values.

I can easily code this but it would probably be more than 3 lines of code. I'm wondering if there is a simple and shorter way.

2 Answers

Get a value between 0 and 9, then add 1 if the value is 5 or more.

val r = Random.nextInt(0, 10)
return if (r < 5) r else r + 1

You could generate a sequence of numbers in the range you care about and take the first one that is not one of the ones you don't care about...

sequence<Int> { (1.. 10).random() }.first { it != 5 }
Related