+ 1
How to use Random to print either "rock", "paper" or "scissors"
Kotlin version
2 Antworten
+ 7
I would extend Iterable to add the method.
// Extend Iterable class with 1.3 random
// method.
fun <T> Iterable<T>.random() =
elementAt(java.util.Random().
nextInt(count()))
fun main(args: Array<String>) {
println(listOf("Rock", "Paper",
"Scissors").random())
}
+ 2
- Create a list of those 3 strings.
- Generate a random integer in range 0 to 2 (inclusive) using java.util.Random class.
- Use randomly generated integer as an index to retrieve element from list.
In kotlin 1.3 you can use list.random() but sololearn is still stuck on 1.1.60 :| so above mentioned approach is ok.