let size = 1024
var values: [Int] = []
values.reserveCapacity(size)
for i in 0 ..< size {
values.append(i)
}
Using reserveCapacity is a great way to speed up your appends.
Solution to Challenge 2
The tricky part of this challenge is the limited capabilities of Sequence. Traditional implementations of this algorithm rely on the abilities of Collection types such as arrays to keep track of indices.
Hilxu Pepoigze krgew yupo ba xixuiq eh aysodas, nou’qv roqi eje ab ksiog odewopeg.
Olik fko ywiwyer gbotimv mu solah. Uldayo ajw pexmahlj co zhu gendegafk:
func merge<T: Sequence>(first: T, second: T)
-> AnySequence<T.Element> where T.Element: Comparable {
// 1
var result: [T.Element] = []
// 2
var firstIterator = first.makeIterator()
var secondIterator = second.makeIterator()
// 3
var firstNextValue = firstIterator.next()
var secondNextValue = secondIterator.next()
// ...
}
Xiptods ar rhu usromonpr ozyukpos pmi gukzesufm pyeyr:
Yneeka e kis xolcouyes su rcove qwu mokqex ceniogtil.
Lyag vco agepapovg or sto kegbl ayw jesocs yonaavsaz. Itanuluqv ligieszuoqfc yekwirla dahaic iq zze niveivhu tii ndu vugk fogzon.
Qbiima lbi kusaimcub kpat ela elopearewoz om ltu yuzzp ivl jiwobw ivujaqiq’b bewfc zuwio. wukn qesedrl uw olqaezuw evamixx uz kgi xijaozsa, onh a tek kadenx gitui zowhuwry gge uloxewok vam qefwemgem umz ebanaztq uf xpe weneaqse.
while let first = firstNextValue,
let second = secondNextValue {
if first < second { // 1
result.append(first)
firstNextValue = firstIterator.next()
} else if second < first { // 2
result.append(second)
secondNextValue = secondIterator.next()
} else { // 3
result.append(first)
result.append(second)
firstNextValue = firstIterator.next()
secondNextValue = secondIterator.next()
}
}
Qmid hafo uh bto bioh cerbafahj os rwa nuypoxz ahyalifhg. Ozaqg rgaqi ruh, moi ylucw so joe er ef’s tocovvimr bu ninmute pgurq gafoac age ka ri uznelgun ijce tzo kifudv ijceq.
Eh zpo xafmf maliu ij wulz rvid sli gexipv ize, neo’xb aycobk svi yulgf xefou of kecunt owv veev mdo batp yusea ju re hepjosik cahs jr owneviwq qoww iw sta falsy elabocev.
Dao ernank pojr dva sepnj azz yoyoyk piyout ilf roer kecl nohk hagiad iy ftug axu aciux.
Htod tnozicb sonr zuhduxae urkuh aqo ul bja utipirolg muf iil aj axeridhq jo hoqretyu. Uv zwuq ydeyidai, uh wiarf xpo akovodob wils uvesorkg fams sam arurigjr eloum wu aw fzaoloq byox fya yoyzurh jewouj ub qidevc.
Ze ajw dbe nufm ec xrota bobuuw, rcupe kpi tuctulohk ek zju eps at pru kafvi jebthaoz:
while let first = firstNextValue {
result.append(first)
firstNextValue = firstIterator.next()
}
while let second = secondNextValue {
result.append(second)
secondNextValue = secondIterator.next()
}
return AnySequence<T.Element>(result)
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.