Skip to content

Instantly share code, notes, and snippets.

@ahcode0919
Last active April 24, 2022 17:49
Show Gist options
  • Save ahcode0919/18257eaef96ff343ad484e56fa80818c to your computer and use it in GitHub Desktop.
Save ahcode0919/18257eaef96ff343ad484e56fa80818c to your computer and use it in GitHub Desktop.
Example of an anagram algorithm in Swift
//Anagram - Two words that contain the same characters
let testWord = "abcde"
let testWord2 = "edcba"
func isAnagram(word word: String, isAnagramOf word2: String) -> Bool {
guard
let word1Dictionary = countChars(word),
let word2Dictionary = countChars(word2) else {
return false
}
for (k, v) in word1Dictionary {
guard v == word2Dictionary[k] else {
return false
}
}
return true
}
func countChars(word: String?) -> [Character: Int]? {
guard let word = word where word != "" else {
return nil
}
var dictionary = [Character: Int]()
for char in word.characters {
if let currentValue = dictionary[char] {
dictionary.updateValue(currentValue + 1, forKey: char)
} else {
dictionary[char] = 1
}
}
return dictionary
}
isAnagram(word: testWord1, isAnagramOf: testWord2)
@SalihKIR
Copy link

iyimiş keke

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