Skip to content

Instantly share code, notes, and snippets.

@MaciejGad
Created September 27, 2018 20:58
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 MaciejGad/9bfd5386c8067701f92c08bcfafca3ab to your computer and use it in GitHub Desktop.
Save MaciejGad/9bfd5386c8067701f92c08bcfafca3ab to your computer and use it in GitHub Desktop.
import Foundation
func add(_ char:Character, to input:String, pattern:[UInt]) -> String {
guard pattern.reduce(0, +) > 0 else { return input }
var str = input
var index:String.Index? = str.startIndex
var i = 0
while index != nil {
let offset = pattern[i%pattern.count]
i += 1
guard offset > 0 else {
continue
}
guard let newIndex = index else {
return str
}
index = str.index(newIndex,
offsetBy: Int(offset),
limitedBy: str.endIndex)
guard let solidIndex = index else {
return str
}
guard solidIndex != str.endIndex else {
return str
}
str.insert(char, at: solidIndex)
index = str.index(solidIndex,
offsetBy:1,
limitedBy: str.endIndex)
}
return str
}
var str = """
Helloplayground,howareyou?
Helloplayground,howareyou?
Helloplayground,howareyou?
"""
let offsets:[UInt] = [6, 11, 3, 3, 4]
let spaced = add(" ", to: str, pattern: offsets)
print(spaced)
print(add("|",to: "aaa", pattern: []))
print(add("|",to: "aaaaaaa", pattern: [0]))
print(add("|", to: "aaaaa", pattern: [0, 0, 0, 0]))
print(add("|", to: "", pattern: []))
print(add("|", to: "aaaaaaa", pattern: [1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment