Created
September 27, 2018 20:58
-
-
Save MaciejGad/9bfd5386c8067701f92c08bcfafca3ab 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
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