Skip to content

Instantly share code, notes, and snippets.

@egzonpllana
Last active February 6, 2021 09:50
Show Gist options
  • Save egzonpllana/0f8671f9122d51f8340a970d4f9d4a8c to your computer and use it in GitHub Desktop.
Save egzonpllana/0f8671f9122d51f8340a970d4f9d4a8c to your computer and use it in GitHub Desktop.
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