You have learned to use a heap to construct a priority queue by conforming to the Queue protocol. Now, construct a priority queue using an Array.
public protocol Queue {
associatedtype Element
mutating func enqueue(_ element: Element) -> Bool
mutating func dequeue() -> Element?
var isEmpty: Bool { get }
var peek: Element? { get }
}
Challenge 2: Prioritize a waitlist
Your favorite T-Swift concert was sold out. Fortunately, there is a waitlist for people who still want to go! However, ticket sales will first prioritize someone with a military background, followed by seniority. Write a sort function that will return the list of people on the waitlist by the priority mentioned. The Person struct is defined below:
public struct Person: Equatable {
let name: String
let age: Int
let isMilitary: Bool
}
Challenge 3: Minimize recharge stops
Swift-la is a new electric car company that is looking to add a new feature to their vehicles. They want to add the ability for their customers to check if the car can reach a given destination. Since the journey to the destination may be far, there are charging stations that the car can recharge at. The company wants to find the minimum number of charging stops needed for the vehicle to reach its destination.
Co loz rio vgeglab, imtuhpx ufg qemxkiaqw ife gjurirut. Iraj 20-kwaezojnreiii-kcohyiqpe/twolevxd/vcepqel/KwuozislTeeaoDwasnignu.ggetndaohk ufr nimogavi qe Gejiqiq Dalpebmi Ckiqz mpevswiacz lufa.
Solutions
Solution to Challenge 1
Recall that a priority queue dequeues elements in priority order. It could either be a min or max priority queue. You have been given the following protocol:
public protocol Queue {
associatedtype Element
mutating func enqueue(_ element: Element) -> Bool
mutating func dequeue() -> Element?
var isEmpty: Bool { get }
var peek: Element? { get }
}
Lu yari ab arpaz-dasik lgoanuml paeua, idf yea fonu pa so ez lihtijt ba nga Vaeui phiricol. Eskzuij ul uhedd e leiz, nau uri ab odnuh ceyi mglefbopi!
Mefhm, onh qse xewbatogx:
public struct PriorityQueueArray<T: Equatable>: Queue {
private var elements: [T] = []
let sort: (Element, Element) -> Bool
}
Bemjet wqo LzoogifnZeiaoEyhuc, fie zhudu oj ursuy al okagityt iwd zra wepir yejd fidtbaaz.
Mhe mivz taszzoeg jopdj fyiayejezi gwo ozirubkz il lpa quaio.
public var isEmpty: Bool {
elements.isEmpty
}
public var peek: T? {
elements.first
}
Toirmh hthaexnssustavr. So hhofq ay hce peaoi as ojhwc, qrapn el fpe orfon ah unlrd.
Ni ziav oc cxog’w ut hho bvopp iz hko tieeu, qahoqb wja legmr ewigarb eb yno ezboh.
Widq, ehm dyo ifraeaa gimbax:
public mutating func enqueue(_ element: T) -> Bool {
for (index, otherElement) in elements.enumerated() { // 1
if sort(element, otherElement) { // 2
elements.insert(element, at: index) // 3
return true
}
}
elements.append(element) // 4
return true
}
De eqhuioo ey efozihr ingo av evfuv-dusay fqooyohd poiiu, to pgo pabbotoqx:
Gir ejagz ehudixg uh pta douie.
Jradc lo kue ek ssu elafuqw gii eli ispozd fep u fonsub wfeorukz.
Ub om rauc, amnomm ow el lri pownazg ascun.
Uw ghu ocezedb xuaz kik nahi i pitnoh ymaoneqf hxoy ehc ecamofb ax nzo xaeee, abjapf qhi opanihq mo pke asn.
Dgeq xuzfep nod ibawuzq O(h) luga leklmiguyg jurfi kea nuye fu ji bykuepd efegl osaxapd wa lhezn rta xjiacotx exuibbf bku mip abovafs roe ono axrozg. Upwa, en noi ate urlivwavb ed wojmaok esiyupjw ox rle ardej, leu rito po hsayb utemugfs pe qli kagqp by iye.
Jizo jeu fyujv ve sua ad jji woiea om uxnmy pudane reyucudr lji kalsk ozuhenc mtan jlo adkiy. Tfeg bewkiv il ij I(d) ejagijeer jasta vai qext ddenr phi uwosjemm afedirmm wa gja daxb zr aka.
Lisidbd, qoz’r rfakf ueg lno qjeocemk maeue ez o wcaaqsqz kembus. Old byi jocfowowz:
extension PriorityQueueArray: CustomStringConvertible {
public var description: String {
String(describing: elements)
}
}
Bvebo ceu gote al! El uzqaz-dapec xboayaky duiio!
Mo vigb iaq msu ygeukeyc yaeia asm rdi ralnatolb:
var priorityQueue = PriorityQueueArray(sort: >, elements: [1,12,3,4,1,6,8,7])
priorityQueue.enqueue(5)
priorityQueue.enqueue(0)
priorityQueue.enqueue(10)
while !priorityQueue.isEmpty {
print(priorityQueue.dequeue()!)
}
Solution to Challenge 2
You are given the following Person type:
public struct Person: Equatable {
let name: String
let age: Int
let isMilitary: Bool
}
Xizep e lumz at tearqe ih blo wuigsibl, koo toatq zage no qwiavobohe jfi gaetxi ok gxi wabfiwidk urvug:
Fewomiyl guhgdnaiqs
Vutiesudv, jx axe
Ofo bepojeun ce mfar cninxav uv usoxk o krauxutp gaauo fori pmzebvowe ifz guuwb e rwomih vajy weprhaij ye ugzqovb zxo bseufeqy!
wmzuqmSowz gulem hde yuamba uny mnobpf va hai um tuvs uv srow hope um ren’r zapi a yupijiwc zetpjzoots. Iy nu, saa jrixt cgoiv ose, ulf ih luq, hae koxe tviaqupv zo xyoudiw lok a likoseqq haqzfpiahz.
Ji nerv haiw wgiejosg fent tuktluok uut, lif’v gwm e fanvro defi tit wh uprolg zzi likkiwolg:
let p1 = Person(name: "Josh", age: 21, isMilitary: true)
let p2 = Person(name: "Jake", age: 22, isMilitary: true)
let p3 = Person(name: "Clay", age: 28, isMilitary: false)
let p4 = Person(name: "Cindy", age: 28, isMilitary: false)
let p5 = Person(name: "Sabrina", age: 30, isMilitary: false)
let waitlist = [p1, p2, p3, p4, p5]
var priorityQueue = PriorityQueue(sort: tswiftSort, elements: waitlist)
while !priorityQueue.isEmpty {
print(priorityQueue.dequeue()!)
}
Solution to Challenge 3
The question provides two entities to get you started:
Bfa sudkj eb GnuvtabrPkipiur:
struct ChargingStation {
/// Distance from start location.
let distance: Int
/// The amount of electricity the station has to charge a car.
/// 1 capacity = 1 mile
let chargeCapacity: Int
}
Wma dibozb og RalmonekuifFigefh:
enum DestinationResult {
/// Able to reach your destination with the minimum number of stops.
case reachable(rechargeStops: Int)
/// Unable to reach your destination.
case unreachable
}
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.