Skip to content

Instantly share code, notes, and snippets.

@jacksonh
Last active August 29, 2015 14:06
Show Gist options
  • Save jacksonh/2cbc12de46e99220ba55 to your computer and use it in GitHub Desktop.
Save jacksonh/2cbc12de46e99220ba55 to your computer and use it in GitHub Desktop.
var words = [ "tea", "dog", "eat", "god", "ate", "bratwurst" ]
//
// pair each word with a unique key of the letters in that word
// by sorting the letters of the word
//
let pairs = words.map { (word) -> (key : String, word : String) in
let key = String (seq: sorted (word))
return (key : key, word: word)
}
//
// Group all the words that have the same set of letters and filter
// out any lists that have less than two entries
//
let anagrams = pairs.reduce ([String:Array<String>](), { (var dict, pair) in
var wordList : Array<String> = dict[pair.key] ?? [];
wordList.append (pair.word)
dict [pair.key] = wordList
return dict;
}).values.filter ({$0.count > 1})
for value in anagrams {
println("Anagrams: \(value)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment