Skip to content

Instantly share code, notes, and snippets.

@omarzer0
Created January 23, 2022 22:01
Show Gist options
  • Save omarzer0/3eddfd01ff315b83a0f9f88aa7bd9554 to your computer and use it in GitHub Desktop.
Save omarzer0/3eddfd01ff315b83a0f9f88aa7bd9554 to your computer and use it in GitHub Desktop.
Fun after an exam with kotlin extension functions to solve simple challenge for solving this challenge.
fun main() {
//abcabc => cba => aa = 2
val two = stringReduceChallenge("abcabc")
println(two)
// aaaa = 4
val four = stringReduceChallenge("aaaa")
println(four)
// abcab => cbb => ab => c = 1
val one = stringReduceChallenge("abcab")
println(one)
}
fun stringReduceChallenge(input: String): Int {
var desiredString = input
while (!desiredString.allStringCharactersAreTheSame()) {
val mList = desiredString.toList()
desiredString = ""
mList.forEachTwo { s1, s2 ->
when {
s1 == s2 -> {
desiredString += "$s1$s2"
}
s2 == null -> {
desiredString += s1
}
else -> desiredString += flip(s1, s2)
}
}
}
return desiredString.length
}
fun flip(s1: Char, s2: Char): Char {
return if (s1 == 'a' && s2 == 'b' || s1 == 'b' && s2 == 'a') {
'c'
} else if (s1 == 'b' && s2 == 'c' || s1 == 'c' && s2 == 'b') {
'a'
} else {
'b'
}
}
fun String.allStringCharactersAreTheSame(): Boolean {
if (this.isEmpty()) return true
// 1- Get the first char
// 2- If there is any char in the string that doesn't
// equal the first char
// then not equal else equal
// note that any returns (true) if any matches the given predicate
// so here if any char doesn't equal the first it returns true
// but from the name of the method it return true if all equals
// very easy just negate the result :) XD
return !any { this.first() != it }
}
/**
* Performs the given action on each two elements.
* if odd size collection is used it will be considered
* as odd collection + 1 null item to make it even
*
* even ex: ['a','b','c','d'] will return:
* => 'a','b'
* => 'c','d'
*
* odd ex: ['a','b','c'] will return:
* => 'a','b'
* => 'c',null
* */
inline fun <T> Collection<T>.forEachTwo(
action: (T, T?) -> Unit
) {
forEachIndexed { i, t ->
if (size == 0) return
if (!isEven(i) && i != 0) {
action(this.elementAt(i - 1), t)
} else if (i == size - 1) { // is last index
action(this.elementAt(i), null)
}
}
}
fun isEven(int: Int) = int % 2 == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment