Skip to content

Instantly share code, notes, and snippets.

@ncomet
Last active April 24, 2021 16:16
Show Gist options
  • Save ncomet/bd09b8beec112a6f42eda8e3a9167adb to your computer and use it in GitHub Desktop.
Save ncomet/bd09b8beec112a6f42eda8e3a9167adb to your computer and use it in GitHub Desktop.
Anagrams in Kotlin
// we create a sequence that generates prime numbers
fun primes(): Sequence<Long> {
var i = 2L
return generateSequence { i++ }
.filter { n -> (2L until n).none { n % it == 0L } }
}
// we map chars to a unique prime
val charToPrime = ('a'..'z').zip(primes().take(26).toList()).toMap()
// we transform a String to its prime product representation
fun String.toPrimeProduct() = this
.filter { it != ' ' }
.map { it.toLowerCase() }
.fold(1L) { acc, c -> acc * charToPrime.getValue(c) }
// finally we simply say that two string are anagrams if their prime product is the same !
infix fun String.isAnagramOf(other: String) = this.toPrimeProduct() == other.toPrimeProduct()
// the infix function can be invoked !
"Clint Eastwood" isAnagramOf "Old West action" // true
"Madonna Louise Ciccone" isAnagramOf "One cool dance musician" // true
"This does not make sense" isAnagramOf "A wild red mongoose" // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment