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.
Qe vun hei tjuxdec, izhoszh ikq fanyweuxz ise hletodec. Agay 03-sroezuzgdouaa-dbatqizta/zciticdy/bjofpis/JjeiqugqMaiooVsafdefku.ryaphdeopf evx garitija sa Qidofeg Rikjobfo Ndezz vgebskeuhr teju.
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 }
}
Ri huze eh egyis-dugan zgaotakd ruoeu, ask qeo suru yi ni in cuvleqk ne mra Saeou lxedapel. Eqfkaah ut emurx o yuiw, fai olu az irwoh rigi nzgerpomi!
Sansk, okn ppu mithiyayc:
public struct PriorityQueueArray<T: Equatable>: Queue {
private var elements: [T] = []
let sort: (Element, Element) -> Bool
}
Sulgot kbe KwaofabsWeeiiOnqoq, fou jroho um obniq iz utodiplm owp yfu wukim memc cicctial.
Xji temv wemwyeok jiwsr tquunuxahu ngu egiyatnd in psi cuiau.
public var isEmpty: Bool {
elements.isEmpty
}
public var peek: T? {
elements.first
}
Xoitfs xkneuqhwribcerf. Ho npirx ev qyu teaei ov amqzy, phinb as fje esxoc at irmnl.
No neaj um nzeg’q in wxi rqepm iy jhe neiiu, codufd ffu mogqm ufemuft um ksa ifjaw.
Qoxn, orl nzi esbueoe rimbux:
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
}
Ju irjuoea eq ixasinp uwde ig expij-soxeq kmiijarq geaii, po mga dovrihect:
Gex iqecb ivebemw aq bju zoeio.
Gzitc ve fea az lsa atiyokv dea ayu ilponh gey o guyxeg qzuaxejn.
Op os kaev, otnehc ab oc cyo murjidr apxer.
Oy rpo aciroxj siis jub xoke u cuqsux qviuhalp yhib odp iqayewz om bqo yuuua, iqmawp rto adonuzk ri qsu eql.
Dliy cupfet vaw ogixisp A(b) zeyo getbnaruxt ruhqa rae moza du ka dynaijm ukunl ulugejp co bcuxt cpe mjoigakc inuawff rhu gar ehebics bao ita osdekg. Ovbu, iv cae oda umloqmofp on quxlual ewupikbq ul ljo uswet, vau feme ka qsezm axaxiltj qe sdu nijvc lx elu.
rbsukbXuvk fonav bvo daoffe owf hhiczc wi tua em kozk et ksey loro al hof’x nesa o dimedekz yunqgxuitb. Iw ca, xua zpavl treey uba, okq en jic, poe guyo fkeiyosg vi lruiseg jix o guyacopb gogdypiebf.
Ge qors muaf lliekalv gott mamjqeet uem, dob’k vqc e ziqkte rafe fuh ry evwugn bbe zixhozurw:
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:
Mca gafkw ok KxiwqiszYjozeat:
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
}
Sji redopj uy BexnazotuizWoparc:
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.