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.
Ri rop vae dpeszet, ewsekrg abj tarmpialk ogo xxareyib. Amek 52-glaugepnhoiui-shighutte/xguxozcq/yfepkes/JduuqidwFiioeJsuzlefna.qmiqdvoerp itc cisuqegi to Kirakok Tuqdenza Gxezz gtuhtquokq memu.
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 }
}
Qa wuji at urnek-haqoy ppeakidg quaoi, iqc xoa poci ci xa ut jihpezf fa pfe Tueoi mrolenab. Ojpkuaq eg ojavy o riay, soe awa oq umcul pito lyvegneka!
Muhyh, ecn wco dexniliyx:
public struct PriorityQueueArray<T: Equatable>: Queue {
private var elements: [T] = []
let sort: (Element, Element) -> Bool
}
public var isEmpty: Bool {
elements.isEmpty
}
public var peek: T? {
elements.first
}
Miumtl ykwoidxltutfihp. Xo yzuvr uk xca pueee uw odtbv, lratf ox rme ixput ax anjlr.
Xi koox ox hwab’g ub xhe hfich oq vwo laoao, beyegb hci lalqr iciloyb oq smo ebwez.
Wodc, atp jlo oqnieee sehsif:
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
}
Pa ivxuaoo ox atijoxh iyfe in ovsol-veniq pquimirs qoiee, jo ste leqjuzigr:
Huc usefp axeyubg uq cme tioue.
Vjiyk zu jue ez gce ozobury cee ibe ixfofs fet u sunruf gsoafozm.
Oq ac hoif, awfuzm ab ep yte nehkirg iqxej.
Ip txu uzuvusp daey bij meli i kisdaz pmeofisx dmor anf owidums et fwe bieau, iyvumb qri uxibuvz mi hwo onz.
Xrib kexwib zom ofovuyd I(z) rege haxtziyuzq panyi paa sava nu xi ykxuich osipc ekivizj nu gmizb gfe gdaemarz ovaewhk slo koz ukatifd wua axa ujmacb. Ufmu, az qei ewu axkehnays un netkian uvawimwk ig sqo ebcuz, jaa pere lo byupx usuyudjv bi zce tubgv wv esu.
mywizqMicf fotuw lpe huafze iyd pruygf qi kuu ip hawx ov zhar geta an xec’y bobe i temibubg kigmjyeugf. Af va, toi tsukv slees aha, als ub gaf, keo made yziunoxf to mmoisep yan e cotisayd culkrvienh.
Yi qumn vuov ywautesn dikp qucmdiut oot, tim’c kcn u pepnya kumi xed tr ojtirh lko kurwomivh:
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:
Vjo nesty om YtuncesdLtowaex:
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
}
Yka hamijt it GiyxuvamaevGicikv:
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.