Just for fun you can use starts with predicate while iterating your first sequence from the end as follow:
let first: [String] = ["A", "B", "F", "E"]
let second: [String] = ["F", "E", "A", "G"]
var pos = first.endIndex
while pos > first.startIndex,
second.starts(with: first[pos...], by: { $0 != $1}),
!second.isEmpty {
first.formIndex(before: &pos)
}
let result = first[..<pos] + second // ["A", "B", "F", "E", "A", "G"]
This will result in a SubSequence, in this case an array slice. If you need an array just explicitly set the resulting type:
let result: [String] = first[..<pos] + second
Based on OP comments if you need to match the subsequence by pairs just offset every two elements:
let first = "ABFF"
let second = "FFAG"
var pos = first.endIndex
while pos > first.startIndex,
second.starts(with: first[pos...], by: { $0 != $1 }),
!second.isEmpty {
first.formIndex(&pos, offsetBy: -2)
}
let result: String = first[..<pos] + second // "ABFFAG"
If you need the string elements separated by spaces:
var first = "A B C D E F G D E"
var second = "D E F C B A"
first.removeAll(where: \.isWhitespace)
second.removeAll(where: \.isWhitespace)
var pos = first.endIndex
while pos > first.startIndex,
second.starts(with: first[pos...], by: { $0 != $1 }),
!second.isEmpty {
first.formIndex(&pos, offsetBy: -2)
}
let result = (first[..<pos] + second)
.map(String.init)
.joined(separator: " ")
result // "A B C D E F G D E F C B A"
edit/update:
Following the logic shown at your last comment/answer you can do something like:
extension RangeReplaceableCollection where Element: Equatable {
mutating func appendAndMerge<C: Collection>(with collection: C) where C.Element == Element {
var lowerBound = startIndex
formIndex(&lowerBound, offsetBy: Swift.min(count, count-collection.count), limitedBy: endIndex)
while !collection.starts(with: self[lowerBound...]) {
formIndex(&lowerBound, offsetBy: 1, limitedBy: endIndex)
}
replaceSubrange(lowerBound..., with: collection)
}
}
Usage:
var first = ["at", "by", "chicken", "dog", "eat", "for", "good", "dog", "eat"]
let second = ["good", "dog", "eat", "feed", "cats", "bonk", "atrophe"]
first.appendAndMerge(with: second)
print(first)
This will print
["at", "by", "chicken", "dog", "eat", "for", "good", "dog", "eat", "feed", "cats", "bonk", "atrophe"]
Using strings (collection of characters)
var first = "at by chicken dog eat for good dog eat"
let second = "good dog eat feed cats bonk atrophe"
first.appendAndMerge(with: second)
print(first)
This will print:
"at by chicken dog eat for good dog eat feed cats bonk atrophe"