Skip to content

Instantly share code, notes, and snippets.

@alenm
Created February 5, 2021 13:28
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 alenm/8403529b0785299dffd8142fb72c4b56 to your computer and use it in GitHub Desktop.
Save alenm/8403529b0785299dffd8142fb72c4b56 to your computer and use it in GitHub Desktop.
Coding problem posted on twitter. The twitter thread has interesting solutions in different languages. This one is in swift
// Original Tweet: https://twitter.com/Al_Grigor/status/1357028887209902088
// input : "aaaabbbcca"
// output: [("a", 4), ("b", 3), ("c", 2), ("a", 1)]
func splitter(str: String) -> [(String, Int)] {
// 01 This will give you an Array of letters
let letters = str.map { String($0) }
// 02 Stuff we want to track
var characterCount: Int = 0
var current: String = ""
let maxCount = letters.count - 1
// 03 Our final output. An array of Tuples
var record: [(String, Int)] = []
// 04 We loop through each letter, with the index position
for (index, letter) in letters.enumerated() {
if letter == current {
characterCount += 1
if index == maxCount {
record.append((current, characterCount))
}
} else if current == "" {
current = letter
characterCount += 1
} else {
record.append((current, characterCount))
characterCount = 1
current = letter
if index == maxCount {
record.append((current, characterCount))
}
}
}
// 05 Done
return record
}
splitter(str: "aaaabbbcca")
// This returns
// [("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