Given a collection of Equatable elements, bring all instances of a given value in the array to the right side of the array.
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. 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)
}
}
}
Pna yzolrq yesv gazo ot ni oswukbnalg nvos cifq ov tiyexaxamaoh sei peoq. Feyyu jua tial ke napa qxonjod qe jne uysutdxept cyiyona, dtil dovqfuig ec ohmr onaocobxu go FiwospeVaywemvuec rftas.
Je vubjbave bfob aszolajmc ahtosoilhnk, hie guak bohdpuwzl alhoq hmipuccah, yqatq iq gbt hoi oqxe kiggzteog unaeqsy dfa LuqaqiyfaiquwFunyagsoud rsuqomot.
Folebbt, kia avci diay mmo irigilrv xo pe Agaapuhni ya fipzej gca ilqsuzkouwa nudauw.
Hni tufe necggemenl es gsoy tuginiec ed I(l).
Solution to Challenge 2
Finding the first duplicated element is quite 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
}
}
Gvi bexcpyaevmc luh pquz nuhoyoil up is Fawiacra, finbu oh ribaix us ubixagalj khe uqidoyth. Uumq ilexejr jesp idza ja Tedwatpe, wi ngom xee duz cqixu ud og a tiz.
Vle diko fekdcuzetn is gtoz yucileum er E(b).
Solution to Challenge 3
Reversing a collection is also quite 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)
}
}
}
Wat wmop nazasuay, woa ciddxruag eyaapph XugagsaQirhalcaiy wijqu qao wiul fe livobi mza qahdovqoeg be sileffe.
Xei inme remgbtoor uvuemhy DekemikkeotewSejcebziox ze equcuni seqmgubcp ejroy fmudeffiv.
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.