public
Last active — forked from joevandyk/anagram.hs

Analyse Anagram

  • Download Gist
Makefile
Makefile
1 2 3 4 5 6 7 8 9 10 11 12 13
all: anagram
 
anagram: anagram.hs
ghc --make anagram.hs # -O2 -funbox-strict-fields
 
FILE=/usr/share/dict/words
 
bench: anagram
time ruby ./anagram.rb < $(FILE)
time ./anagram < $(FILE)
 
clean:
-rm anagram anagram.hi anagram.o
anagram.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import Data.List
import qualified Data.Map as Map
import Data.Ord
 
main = do
input <- getContents
print $ take 3 $ anagrams $ lines input
 
anagrams words =
sortBy (flip $ comparing length) . Map.elems $ all_anagrams
where
all_anagrams = foldl' insert_word Map.empty words
insert_word map word =
Map.insertWith' (flip (++)) (sort word) [word] map
anagram.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
input = $stdin.readlines
result = Hash.new([])
input.each do |word|
word.chomp!
sorted_word = word.chars.sort.join
result[sorted_word] += [word]
end
 
# To get same output as haskell, Comment in these lines
# (but it makes this script 2x slower)
# values = result.sort { |a, b| r = b[1].size <=> a[1].size; r == 0 ? a[0] <=> b[0] : r }
# .map { |e| e[1] }
values = result.values.sort { |a, b| b.size <=> a.size }
 
p values.take(3)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.