aballano
03/18/2019, 1:35 PM[1, 2, 3]
and [4, 5, 6, 7]
is there an existing function that intercalates both so the result is [1, 4, 2, 5, 3, 6, 7]
?fun <E> List<E>.merge(other: List<E>): List<E> {
val out = ArrayList<E>(size + other.size)
forEachIndexed { index, e ->
out.add(e)
if (index < other.size) out.add(other[index])
}
return out
}
diesieben07
03/18/2019, 1:40 PMla.zip(lb) { a, b -> listOf(a, b) }.flatten()
almost works, in that it only keeps the length of the shortest listwbertan
03/18/2019, 1:40 PM@Test
fun asas1() {
val l1 = listOf(1, 2, 3)
val l2 = listOf(4, 5, 6, 7)
val expected = listOf(1, 4, 2, 5, 3, 6, 7)
val result =
l1.zip(l2).flatMap { listOf(it.first, it.second) } +
l1.drop(l2.size) + l2.drop(l1.size)
assertEquals(expected, result)
}
@Test
fun asas2() {
val l1 = listOf(4, 5, 6, 7)
val l2 = listOf(1, 2, 3)
val expected = listOf(4, 1, 5, 2, 6, 3, 7)
val result =
l1.zip(l2).flatMap { listOf(it.first, it.second) } +
l1.drop(l2.size) + l2.drop(l1.size)
assertEquals(expected, result)
}
fun <T> List<T>.mix(other: List<T>) =
this.zip(other).flatMap { listOf(it.first, it.second) } +
this.drop(other.size) + other.drop(this.size)
ribesg
03/18/2019, 1:46 PMaballano
03/18/2019, 2:42 PMPavlo Liapota
03/18/2019, 3:08 PM[1, 4, 2, 5, 3, 6]
instead of [1, 4, 2, 5, 3, 6, 7]
for your example.ribesg
03/18/2019, 3:27 PMfun <T> Iterable<T>.alternateWith(other: Iterable<T>): Iterable<T> =
Iterable {
object : Iterator<T> {
private val a = this@alternateWith.iterator()
private val b = other.iterator()
private var switch = false
override fun hasNext(): Boolean =
a.hasNext() || b.hasNext()
override fun next(): T {
switch = !switch
return if (switch) next(b, a) else next(a, b)
}
private fun next(first: Iterator<T>, second: Iterator<T>): T =
if (first.hasNext()) first.next() else second.next()
}
}