https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dave08

01/24/2023, 4:49 PM
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

Sam

01/24/2023, 4:51 PM
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

Vampire

01/24/2023, 4:55 PM
Or use
generateSequence
👍🏼 1
👍 3
c

Casey Brooks

01/24/2023, 4:55 PM
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

Vampire

01/24/2023, 4:56 PM
Copy code
generateSequence { Random.nextInt(15) }
    .chunked(2)
    .take(6)
👍 2
d

dave08

01/24/2023, 5:03 PM
Thanks, that was a bit confusing at first, now it's clear!
c

CLOVIS

01/24/2023, 5:05 PM
Copy code
sequence {
    repeat(6) {
        yield(listOf(Random.nextInt(15), Random.nextInt(15)))
    }
}
is more readable IMO
v

Vampire

01/24/2023, 5:07 PM
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

CLOVIS

01/24/2023, 5:07 PM
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

Vampire

01/24/2023, 5:08 PM
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

dave08

01/24/2023, 7:45 PM
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
12 Views