Zorgan
Zorgan

Reputation: 9153

Random().nextInt() not zero-based numbering?

import java.util.*

I'm trying to generate a random string from my array:

val days = arrayOf("Tuesday", "Thursday", "Saturday")
val chosenDay = days[Random().nextInt(2)]

However days[Random().nextInt(2)] only seems to return Tuesday and Thursday. I couldn't find the answer anywhere but why is nextInt() not using zero-based numbering?

I changed it to days[Random().nextInt(3)] and now it's working fine.

Upvotes: 2

Views: 734

Answers (2)

Roland Illig
Roland Illig

Reputation: 41676

As is typical for Kotlin, there are a lot of extension functions for typical use cases. Like here, getting a random element from an array or a collection.

In your case, the simplest code is:

val chosenDay = days.random()

Or, if you need more control about the randomness:

val chosenDay = days.random(Random(12345))   // for testing

The reason that Random.nextInt(n) generates a zero-based random number is that it can be conveniently used in expressions like this:

val chosenDay = days[Random().nextInt(days.size)]

Upvotes: 0

Kroltan
Kroltan

Reputation: 5156

It's not about zero- or one-based indexing (if it was, you would only get "Thursday" or "Saturday"), but that nextInt takes the exclusive upper bound. That is, nextInt(3) returns a number less than 3.

This is a convention compatible with zero-indexing, in fact, since it means you can use the array's length as the upper bound to get a random element of the array.

Upvotes: 7

Related Questions