+ 1

How to use Random to print either "rock", "paper" or "scissors"

Kotlin version

14th Sep 2020, 9:06 AM
dign_code
dign_code - avatar
2 Answers
+ 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()) }
17th Sep 2020, 2:57 AM
John Wells
John Wells - avatar
+ 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.
14th Sep 2020, 10:13 AM
šŸ‡®šŸ‡³OmkaršŸ•‰
šŸ‡®šŸ‡³OmkaršŸ•‰ - avatar