Skip to content

Instantly share code, notes, and snippets.

@codeOfRobin
Created May 5, 2019 09:46
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 codeOfRobin/8c016bd579f96d30c2490b1fa93155f9 to your computer and use it in GitHub Desktop.
Save codeOfRobin/8c016bd579f96d30c2490b1fa93155f9 to your computer and use it in GitHub Desktop.
import Foundation
import XCTest
func isPermutationOfPalindrome(_ string: String) -> Bool {
let characterCounts: [Character: Int] = string.reduce(into: [:], { (dict, character) in
dict[character] = (dict[character] == nil) ? 1 : (dict[character] ?? 0) + 1
})
// Do I really need to do this? 🤔
let keys = Array(characterCounts.keys)
let firstIndex = keys.firstIndex { (characterCounts[$0] ?? 0) % 2 != 0 }
guard let nonNullFirstIndex = firstIndex else {
return true
}
if nonNullFirstIndex == keys.endIndex {
return true
}
let secondIndex = keys[(nonNullFirstIndex + 1)...].firstIndex { (characterCounts[$0] ?? 0) % 2 != 0 }
return secondIndex == nil
}
class PalindromeTests: XCTestCase {
let words: [String: Bool] = [
"abuttuba": true,
"acaramanamaraca": true,
"aladnamedemandala": true,
"asdfghj": false,
"hannah": true,
"civic": true,
"racecar": true,
"anahhn": true
]
func testWithLotsOfWords() {
for (key, value) in words {
print("Testing for \(key)")
print("result is \(isPermutationOfPalindrome(key))")
XCTAssertEqual(isPermutationOfPalindrome(key), value)
}
}
}
PalindromeTests.defaultTestSuite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment