How to use Random to print either "rock", "paper" or "scissors" | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 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 Réponses
+ 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