Last active
February 6, 2021 09:50
-
-
Save egzonpllana/0f8671f9122d51f8340a970d4f9d4a8c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var countCharactersInRow = getCharactersInARowCount(fromString: "aaaabbbcca") | |
func getCharactersInARowCount(fromString string: String) -> [[Character: Int]] { | |
print("Given string: ", string) | |
guard !string.isEmpty else { return []} | |
let charactersArray: [Character] = string.map { $0 } | |
var collectedData: [[Character: Int]] = [] | |
var lastCharacter: Character = charactersArray.first! | |
var arrayPossition: Int = 0 | |
charactersArray.forEach { (character) in | |
lastCharacter = character | |
if collectedData.isEmpty { | |
collectedData.append([character:1]) | |
} else { | |
if lastCharacter == character, let characterValue = collectedData[arrayPossition][character] { | |
collectedData[arrayPossition][character] = characterValue + 1 | |
} else { | |
collectedData.append([character: 1]) | |
arrayPossition += 1 | |
} | |
} | |
} | |
print("Result for given string: ", collectedData) | |
return collectedData | |
} | |
// Console prints: | |
// Given string: aaaabbbcca | |
// Result for given string: [["a": 4], ["b": 3], ["c": 2], ["a": 1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment