What would be the kotlin way to write below code: ```var toPlayer = players.random() ...
s
What would be the kotlin way to write below code:
Copy code
var toPlayer = players.random()
                while (toPlayer == fromPlayer) {
                    toPlayer = players.random()
}
I am not liking the multiple assignments + var here...
s
How about something like
Copy code
val toPlayers = generateSequence {players.random()}.filter {it != fromPlayer}
that gives you an infinite stream of players that are not
fromPlayer
s
interesting. just what I needed. Thank you!
n
make sure there are at least two players ๐Ÿ˜…
I guess that's a requirement regardless
r
(players - fromPlayer).random()
โž• 1
s
nice!
n
it does duplicate the array, but also who cares ๐Ÿ™‚
๐Ÿค” 1
๐Ÿ˜‚ 1
r
You could also define a helper function like so:
Copy code
fun <T> List<T>.randomBut(exclude: T): T {
    var value: T
    do value = random() while (value == exclude)
    return value
}
Then just do
Copy code
players.randomBut(fromPlayer)
Or more general:
Copy code
inline fun <T> List<T>.randomWhere(predicate: (T) -> Boolean): T {
    var value: T
    do value = random() while (!predicate(value))
    return value
}
And
Copy code
players.randomWhere { it != fromPlayer }
s
yes. thats doable. But I didnt want to write the do while + var combo, even in a helper, myself.
r
Fair enough, and not worth it for a single use, but with keeping in mind if you find yourself doing it a lot.
n
I've never seen a one-liner do-while loop before...huh
๐Ÿ‘ 1
s
Me too. I thought this do while + assignment was only possible in Java.
๐Ÿณ๏ธโ€๐ŸŒˆ 1
b
See
Copy code
doWhileStatement
(used by loopStatement)
  : 'do' controlStructureBody? 'while' '(' expression ')'
  ;
in https://kotlinlang.org/docs/reference/grammar.html#whileStatement
๐Ÿคฏ 1
you can even write: "do while (value == exclude)"
and it is valid grammarโ€ฆ
m
anything with random that can't mutually exclude itself from the edge case where it needs to check again is bad in my opinion. in that case I feel that the following code from Ruckus is the best
Copy code
(players - fromPlayer).random()
Yes you could technically use some sort of smart indexer where you exclude the result, but that would include searching for that element in the first place so the complexity would be the same.