Skip to content

Instantly share code, notes, and snippets.

@BradB132
Last active January 17, 2022 21:02
Show Gist options
  • Save BradB132/d91bf1cc28334023888f1bbf1b0fb444 to your computer and use it in GitHub Desktop.
Save BradB132/d91bf1cc28334023888f1bbf1b0fb444 to your computer and use it in GitHub Desktop.
import Foundation
// Get the Unix list of all words.
let words = try! String(contentsOfFile: "/usr/share/dict/words")
.split(whereSeparator: \.isNewline).map({ $0.uppercased() })
// Calculate frequencies of each letter in the above corpus of words.
var wordFrequencies:[String.Element: Int] = [:]
for word in words {
// Only look at 5-letter words.
if word.count != 5 {
continue
}
word.forEach({wordFrequencies[$0] = (wordFrequencies[$0] ?? 0) + 1})
}
var results:[(word:String, score:Int)] = []
for word in words {
// Only look at 5-letter words with all unique characters.
if word.count != 5 || Set(word).count != 5 {
continue
}
// Score each one by adding the values of letters in that word.
let score = word.reduce(0) { partialResult, character in
partialResult + (wordFrequencies[character] ?? 0)
}
results.append((word, score))
}
results.sort(by: {$0.score > $1.score})
print(results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment