Skip to content

Instantly share code, notes, and snippets.

@ProbablyRusty
Created June 19, 2017 05:17
Show Gist options
  • Save ProbablyRusty/c73dc8bf7cbe769a88f8ab8dd77f1353 to your computer and use it in GitHub Desktop.
Save ProbablyRusty/c73dc8bf7cbe769a88f8ab8dd77f1353 to your computer and use it in GitHub Desktop.
Swift Condensing Sentences
// In reference to:
// https://www.reddit.com/r/dailyprogrammer/comments/6grwny/20170612_challenge_319_easy_condensing_sentences/
let input = """
Deep episodes of Deep Space Nine came on the television only after the news.
Digital alarm clocks scare area children.
"""
var lines = input.split(separator: "\n")
for line in lines {
let origSentence = line.split(separator: " ")
var sentence = origSentence.map { String($0) }
func compressWords (_ first: String, _ second: String) -> String? {
var output: String? = nil
for i in 1...first.count {
let range = first.index(first.endIndex, offsetBy: -i)..<first.endIndex
let checkString = String(first[range])
if second.hasPrefix(checkString) {
output = checkString
}
}
return output
}
for index in 0..<sentence.count - 1 {
if let discard = compressWords(sentence[index], sentence[index+1]) {
let trimmedWord = String(sentence[index+1].dropFirst(discard.count))
sentence[index+1] = trimmedWord
} else {
sentence[index] = sentence[index] + " "
}
}
print(sentence.joined(separator: ""))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment