Ch8n
10/21/2023, 7:21 AMSam
10/21/2023, 7:53 AMvararg
just for fun 😄
fun mergeAlternately(vararg strings: String): String = buildString {
val iterators = strings.map { it.iterator() }
do {
var shouldContinue = false
for (iterator in iterators) {
if (iterator.hasNext()) {
append(iterator.nextChar())
shouldContinue = true
}
}
} while (shouldContinue)
}
zip
can't be customised to alter the behaviour when the strings are different lengths 😞Ch8n
10/21/2023, 8:01 AMSam
10/21/2023, 8:10 AMCh8n
10/21/2023, 2:12 PMephemient
10/21/2023, 3:17 PMsuspend fun mergeAlternately(word1: String, word2: String): String = buildString {
merge(
word1.toList().asFlow().onEach { delay(99) },
word2.toList().asFlow().onEach { delay(100) },
).collect(::append)
}
has a chance of working as long as the strings aren't too longfun mergeAlternately(word1: String, word2: String): String =
(word1.withIndex() + word2.withIndex())
.sortedBy { it.index }
.joinToString("") { it.value.toString() }
Pedro Pereira
10/21/2023, 4:05 PMfun mergeAlternately(word1: String, word2: String): String = buildString {
val minLength = minOf(word1.length, word2.length)
fun appendRemainder(word: String) {
for(index in minLength..<word.length)
append(word[index])
}
for(index in 0..<minLength) {
append(word1[index])
append(word2[index])
}
appendRemainder( if (minLength == word1.length) word2 else word1 )
}
ephemient
10/21/2023, 4:31 PMfun mergeAlternately(word1: String, word2: String): String = buildString {
repeat(maxOf(word1.length, word2.length)) {
word1.getOrNull(it)?.let(::append)
word2.getOrNull(it)?.let(::append)
}
}