How do I get a list of two random numbers 6 times?...
# getting-started
d
How do I get a list of two random numbers 6 times? This doesn't work:
Copy code
sequence<Int> { yield(Random.nextInt(0..15)) }
    .chunked(2)
    .take(6)
My goal is something like
listOf(listOf(0, 3), listOf(5, 15), ...)
with six inner lists
s
List(6) { List(2) { Random.nextInt() } }
👍 1
Your example doesn't work because the sequence will only yield once. I think you could fix it by adding an infinite loop.
v
Or use
generateSequence
👍🏼 1
👍 3
c
sequence<Int> { yield(Random.nextInt(0..15)) }
only ever emits a single element, and then quits. Sequences aren’t automatic generator functions, you’ll need to do the iteration within
sequence { }
yourself. Try this, with manual iteration: https://pl.kotl.in/R_efr6krJ Or with `generateSequence`: https://pl.kotl.in/tudLVa1wA
v
Copy code
generateSequence { Random.nextInt(15) }
    .chunked(2)
    .take(6)
👍 2
d
Thanks, that was a bit confusing at first, now it's clear!
c
Copy code
sequence {
    repeat(6) {
        yield(listOf(Random.nextInt(15), Random.nextInt(15)))
    }
}
is more readable IMO
v
More readable than
Copy code
sequence {
    repeat(6) {
        yield(List(2) { Random.nextInt(15) })
    }
}
or
Copy code
List(6) { List(2) { Random.nextInt(15) } }
? o_O
1
c
Ahah no, I meant than the
generateSequence
one. Indeed that double
List
factory one is great
It's not lazy, but it doesn't look like that was the question anyway
v
Yeah, just wanted to stay near to original code to show how to do it properly that way in case it was oversimplified. 🙂
👍 1
👍🏼 1
d
Yeah there are a few chained operators after that sequence generation, so a list would just recreate another list for each operation... That's why maybe the sequence version might be better here... Thanks all for the great ideas 😁, different techniques are always useful for different contexts