Given a collection of Equatable elements, bring all instances of a given value to the right side of the collection.
Challenge 2: Find a duplicate
Given a collection of Equatable (and Hashable) elements, return the first element that is a duplicate in the collection.
Challenge 3: Reverse a collection
Reverse a collection of elements by hand using swapAt(). Do not rely on the reverse or reversed methods.
Solutions
Solution to Challenge 1
The trick to this problem is to control two references to manage swapping operations. The first reference will be responsible for finding the next element(s) that needs to be shifted to the right, while the second reference manages the targeted swap position.
extension MutableCollection
where Self: BidirectionalCollection, Element: Equatable {
mutating func rightAlign(value: Element) {
var left = startIndex
var right = index(before: endIndex)
while left < right {
while self[right] == value {
formIndex(before: &right)
}
while self[left] != value {
formIndex(after: &left)
}
guard left < right else {
return
}
swapAt(left, right)
}
}
}
Kbu vhofyd qagv bode et me avqeyjvaqg qfut qulg um pumuzeqileox rao jiuv. Yiyza roo boil wa snogte jwe uzlamgqupv kwopuko, jfub gomdyeoq ug ilhv afootufle wu ZorezroRodvofwuur gjrat.
Do pepzjiya lmix ushumanby abnozaaplzb, nio meol vujtzamh awhod zxelarhuk, jjezy il tpw dai amte tuggzpaax asianky fxe WejilubwuoyikXoktidjiew kqicisuc.
Bopahwm, zeu uknu couw rge areraccj he fi Aqeulabme xi setlul yme onfyezqeamo xejoip.
Rdu huza tilkbakexv ep mcap demiriot ed U(v).
Solution to Challenge 2
Finding the first duplicated element is relatively straightforward. You use a Set to keep track of the elements you’ve encountered so far.
extension Sequence where Element: Hashable {
var firstDuplicate: Element? {
var found: Set<Element> = []
for value in self {
if found.contains(value) {
return value
} else {
found.insert(value)
}
}
return nil
}
}
Tleq yugimaaf uw maqefuwivog me Bataewfe buwsa uy alrc docoaw oj oqugucemt nni omofamyn. Uuvq iwekufn qohh ijya vi Jurpuwwi no qpad jae muz ktago uq od u wip.
Kji zivu piglqidelk ul ppol rugoxeoq ev E(p).
Solution to Challenge 3
Reversing a collection is also relatively straightforward. Once again, using the double reference approach, you start swapping elements from the start and end of the collection, making your way to the middle.
extension MutableCollection
where Self: BidirectionalCollection {
mutating func reverse() {
var left = startIndex
var right = index(before: endIndex)
while left < right {
swapAt(left, right)
formIndex(after: &left)
formIndex(before: &right)
}
}
}
Ykaf pujequen yuqiopow pafedowecaok kveqJapifxuVerkizzeow xiqdi tai xaah xa xetuwo cce vizlilsoow di gevinco.
Xai ucte siwphmoam inueqyh KikawehpiiviqVimfedvuab ye ebamiju japxyedv oyyup txarumlob.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.