Last active
April 24, 2022 17:49
-
-
Save ahcode0919/18257eaef96ff343ad484e56fa80818c to your computer and use it in GitHub Desktop.
Example of an anagram algorithm in Swift
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
//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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
iyimiş keke