Skip to content

Instantly share code, notes, and snippets.

@msiddiqi
Created February 16, 2020 20:04
Show Gist options
  • Save msiddiqi/8ea6dc21ba062ee9fd4ce452c2a8dcad to your computer and use it in GitHub Desktop.
Save msiddiqi/8ea6dc21ba062ee9fd4ce452c2a8dcad to your computer and use it in GitHub Desktop.
checking if two strings are anagrams
def areAnagrams(first: String, second: String) = {
(first, second) match {
case x if first.length != second.length => false
case _ => {
val firstGroup = first.groupBy(i => i).map { case (item, repetitions) => (item, repetitions.size) }
val secondGroup = second.groupBy(i => i).map { case (item, repetitions) => (item, repetitions.size) }
firstGroup.size == secondGroup.size &&
firstGroup.forall(item => item._2 == secondGroup.getOrElse(item._1, 0))
}
}
}
println(areAnagrams("FRIED", "FIRED")) // TRUE
println(areAnagrams("SPEECH", "SPIECH")) // FALSE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment