really simple programming question: whats the mos...
# announcements
g
really simple programming question: whats the most elegant way to pad out a list with its own elements until a given size is reached? eg:
Copy code
conciseExpr(listOf("A", "B"), 5) //output: [A, B, A, B, A]
conciseExpr(listOf("A", "B"), 2) //output: [A, B]
conciseExpr(listOf("A", "B"), 1) //output: [A]
you are gaurenteed that the input list is non-empty so far I'm working with
Copy code
val output = inputList
        .let { partial -> (0 until 1+(inputTargetSize / partial.size)).map { partial }.flatten() }
        .take(inputTargetSize)
but i feel like
0 until 1+expr
is cloogy
if i had an infinite sequence constant somewhere:
Copy code
PositiveIntegersInfSeq
    .map { idx -> inputList[idx % inputList.size] }
    .take(inputTargetSize)
    .toList()
which seems pretty elegant
also assuming sequence has a
MapIndexed
operator...
n
I forget the best way to do this, but you could also have some kind of
(0..inputTargetSize).map { inputList[it % inputList.size] }
thing
n
@groostav usually this would be its own function IME
E.g. in python this is called cycle I believe, it's in itertools
It is pretty odd that Kotlin doesn't even seem to provide an infinite sequence of integers
That's a pretty common building block
I'd probably write those utility sequences and name them. Either way can use https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/sequence.html
That said you could do a non sequence approach here
Copy code
0..4.map { inputList [it % myList.length] }
n
...hey, that's what I said 😛 but yeah I thought there was a Java or Kotlin way of cycling a list indefinitely
relevant StackOverflow question
n
ah my bad max
e
Copy code
fun <T> Iterable<T>.cycle(): Sequence<T> = sequence {
    while (true) {
        yieldAll(this@cycle)
    }
}

listOf("A", "B").cycle().take(5).toList() // => [A, B, A, B, A]
n
change
while(true) {
to
repeat(2) {
and you have the
.bicycle
extension
n
hah
nice, I didn't know iterable had cycle
i wonder if you're already implementing it though, if its better to do something like yieldAll which probably adds another wrapper, or just write it out
probably doesn't matter
Hmm I don't think I understand what that
this@cycle
syntax is doing
e
within
sequence(block: suspend SequenceScope<T>.() -> Unit)
lambda,
this
would refer to the
SequenceScope<T>
receiver
this@cycle
means "the
this
from the
cycle
scope
just like Java's
Outer.this
in
class Outer { class Inner { { System.out.println(Outer.this); } } }
n
gotcha. I actually understand now. Thanks for explaining!
Very clean
one big advantage of this approach is that you don't need to do any integer moduli
which are expensive