+ 3

Kotlin Beginner - Random Element from Array

Hello all! I'm completely new to coding, but it's something I have been meaning to learn for some time. Starting with Kotlin because I'm interested in Android development - I hear a lot of good things about the language in comparison to Java, and the syntax certainly seems easier for beginners. I'm really enjoying the course here on SoloLearn! I've been playing with arrays recently - I have managed to write the attached, which returns an element from an array based on user input. What I would like to do is generate a random number within a range, which I think would allow me to display a random element from the array. Is anyone able to point me in the right direction here? (P.S. Feedback is very welcome if I have done anything wrong!) https://code.sololearn.com/cSU9aPws1LRE/?ref=app

2nd Jul 2018, 10:31 PM
Laura Hargreaves
Laura Hargreaves - avatar
7 Respuestas
+ 7
3rd Jul 2018, 1:49 AM
John Wells
John Wells - avatar
+ 2
3rd Jul 2018, 12:37 PM
Laura Hargreaves
Laura Hargreaves - avatar
+ 1
Using the random code, this extends a shuffled for Int. // Extend Iterable<Int> with a shuffled function. fun Iterable<Int>.shuffled(): List<Int> {     var count = this.count()     var list = MutableList(count, {-1})     for (loop in 0 until count) {         var index = rand(0, count-1)         while (list[index] != -1)             index = (index+1)%count         list[index] = loop     } // for     for (loop in 0 until count)         list[loop] = this.elementAt(list[loop])     return list.toList() } // shuffled
3rd Jul 2018, 3:43 PM
John Wells
John Wells - avatar
0
Ah, thanks guys! I had actually already tried the 'shuffled' extension after finding this via a Google search, but this didn't work - seems like could have been the compiler rather than me... ;-) I tried to implement John's solution in my code, but I'm getting errors! Can anyone perhaps point out where I've gone wrong?! https://code.sololearn.com/cSU9aPws1LRE/?ref=app
3rd Jul 2018, 12:07 PM
Laura Hargreaves
Laura Hargreaves - avatar