Created
May 5, 2019 09:46
-
-
Save codeOfRobin/8c016bd579f96d30c2490b1fa93155f9 to your computer and use it in GitHub Desktop.
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
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