Last active
August 29, 2015 14:06
-
-
Save jacksonh/2cbc12de46e99220ba55 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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