How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Nim 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 Nim programming language
Source code in the nim programming language
import algorithm
import tables
import times
var anagrams: Table[seq[char], seq[string]] # Mapping sorted_list_of chars -> list of anagrams.
#---------------------------------------------------------------------------------------------------
func deranged(s1, s2: string): bool =
## Return true if "s1" and "s2" are deranged anagrams.
for i, c in s1:
if s2[i] == c:
return false
result = true
#---------------------------------------------------------------------------------------------------
let t0 = getTime()
# Build the anagrams table.
for word in lines("unixdict.txt"):
anagrams.mgetOrPut(sorted(word), @[]).add(word)
# Find the longest deranged anagrams.
var bestLen = 0
var best1, best2: string
for (key, list) in anagrams.pairs:
if key.len > bestLen:
var s1 = list[0]
for i in 1..list.high:
let s2 = list[i]
if deranged(s1, s2):
# Found a better pair.
best1 = s1
best2 = s2
bestLen = s1.len
break
echo "Longest deranged anagram pair: ", best1, " ", best2
echo "Processing time: ", (getTime() - t0).inMilliseconds, " ms."
You may also check:How to resolve the algorithm Sequence: smallest number with exactly n divisors step by step in the J programming language
You may also check:How to resolve the algorithm Date format step by step in the Python programming language
You may also check:How to resolve the algorithm Object serialization step by step in the Haskell programming language
You may also check:How to resolve the algorithm Golden ratio/Convergence step by step in the Phix programming language
You may also check:How to resolve the algorithm Colour bars/Display step by step in the Common Lisp programming language