Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briancordanyoung/a59b7a87c1eccea55b9b04f116e7fbe9 to your computer and use it in GitHub Desktop.
Save briancordanyoung/a59b7a87c1eccea55b9b04f116e7fbe9 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Cocoa
// Generate the appropriate integer value for each character using
// a the ascii value from the return unicodeScalars.
// UInt8 (Unsigned 8 bit Integer)
// a | A = 1
// z | Z = 26
// all others will be 0
extension Character {
var letterValue: Int {
// We only want to give a value to the characters a-z and A-Z.
guard let scaler = self.unicodeScalars.first else { return 0 }
let value = Int(UInt8(ascii: scaler))
// unicodeScalars ascii values
// a = 97
// z = 122
// A = 65
// Z = 90
let uppercaseOffset = 64
let lowercaseOffset = 96
// Uppercase letters
if (value >= 65) && (value <= 90) {
return value - uppercaseOffset
}
// lowercase letters
if (value >= 97) && (value <= 122) {
return value - lowercaseOffset
}
// character was outside of the a-z | A-Z characger set and it has no value.
return 0
}
}
extension String {
// return the value for a string, assuming it is a word.
var wordValue: Int {
return self.map { $0.letterValue }
.reduce(0, +)
}
// break a string into words by spliting on a space character.
var words: [String] {
// TODO: handle complex words with spaces i.e.: names like Mc Donald
return self.components(separatedBy:" ")
}
// break a string into lines of string by spliting on a new line character.
var lines: [String] {
// TODO: handle other line endings
return self.components(separatedBy:"\n")
}
}
do {
let dictionary = try String(contentsOfFile: "/usr/share/dict/web2")
let wordsWithValue100 = dictionary.lines.filter { $0.wordValue == 100 }
print("Dictionary has " + String(wordsWithValue100.count) + " words that equal 100.") // Dictionary has 2302 words that equal 100.
} catch {
print("Failed to read the dictionary")
}
@briancordanyoung
Copy link
Author

Dictionary has 2302 words that equal 100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment