How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Scala programming language
Table of Contents
Problem Statement
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Use the word list at unixdict to find and display the longest deranged anagram.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Scala programming language
Source code in the scala programming language
object DerangedAnagrams {
/** Returns a map of anagrams keyed by the sorted characters */
def groupAnagrams(words: Iterable[String]): Map[String, Set[String]] =
words.foldLeft (Map[String, Set[String]]()) { (map, word) =>
val sorted = word.sorted
val entry = map.getOrElse(sorted, Set.empty)
map + (sorted -> (entry + word))
}
/* Returns true if the pair of strings has no positions with the same
* characters */
def isDeranged(ss: (String, String)): Boolean =
ss._1 zip ss._2 forall { case (c1, c2) => c1 != c2 }
/* Returns pairwise combination of all Strings in the argument Iterable */
def pairWords(as: Iterable[String]): Iterable[(String, String)] =
if (as.size < 2) Seq() else (as.tail map (as.head -> _)) ++ pairWords(as.tail)
/* Returns the contents of the argument URL as an Iterable[String], each
* String is one line in the file */
def readLines(url: String): Iterable[String] =
io.Source.fromURL(url).getLines().toIterable
val wordsURL = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
def main(args: Array[String]): Unit = {
val anagramMap = groupAnagrams(readLines(wordsURL))
val derangedPairs = anagramMap.values flatMap (pairWords) filter (isDeranged)
val (w1, w2) = derangedPairs maxBy (pair => pair._1.length)
println("Longest deranged pair: "+w1+" and "+w2)
}
}
You may also check:How to resolve the algorithm P-value correction step by step in the Raku programming language
You may also check:How to resolve the algorithm Word frequency step by step in the 11l programming language
You may also check:How to resolve the algorithm Random number generator (included) step by step in the TI-83 BASIC programming language
You may also check:How to resolve the algorithm State name puzzle step by step in the Python programming language
You may also check:How to resolve the algorithm Safe primes and unsafe primes step by step in the D programming language