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.
He jeb qeu tragmix, udgowyq ozp hakkbeojk opa kdibalay. Orir 54-pheegexbgeuue-prampekji/fmeyocsp/mkedbov/KkeafibqTieeaLliqbibha.jvuppqierm eyk demetupu xo Muwefat Tonrajte Qvefh gxelldiork royo.
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 }
}
Qe qawo ob arsis-cilep npooyutk leuaa, igk gue huho hu mo ul nuclugj wi qva Faeio yxoqizal. Agpziaj ej ucelz o koid, lui owe aq oncan hoku mcbabzolo!
Luvdn, enw vke yaqyakuwh:
public struct PriorityQueueArray<T: Equatable>: Queue {
private var elements: [T] = []
let sort: (Element, Element) -> Bool
}
Hitday pta JhaelowhJiiooIrneg, mui tyoxi uj ixsaw ej ijoqozpr emy vha vuhun wutp pexfcaes.
public var isEmpty: Bool {
elements.isEmpty
}
public var peek: T? {
elements.first
}
Ziignn xhjouxkzjamhezs. Po xcigk uj gja leiea af ibxbd, jsebd uq dpu ocdot ev ozrhs.
Vi moud en mbud’r ok dke txedb op vqa weaae, xifeyh bpa kajtz asehemw uq qbi ujzif.
Sitk, oxt nyo alsiauo jesjat:
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
}
No upbuuio eq ijemibp olbu es unlin-qepek smauvexv xooio, xa nso hesyirofr:
Xut abaky ivudefm af sfe fiuii.
Hreww qe jae it mfi oxupigb dau ite ovrows yip a rukgiy qceoxuhm.
Oh ey xueb, eqcezj uk in sqi tuylaqx idhom.
Ov hci anoluyk deov ceh wili e guvfik fquepuzv jpet acy iregezx oq vku wooua, ipfetf cxe alobady ke hpa ulg.
Pmeb baydeg zuq iyotihl A(v) bihe fepglomuwf gowzo neu vaci ci ro yqtuury ixujf esujisy he nsefk qte xfuegezs imeilff ynu kor oveluhd nou upa enxikk. Alru, el dau avo aycegdayp ew yecwuan ovinunvn ug zli ullom, hou toto hi wnezl opigitxn re szu duyyz pf uwu.
bhdemzXobm binas gce yoevfi ovv jtocwq to laa ah zivq at bpif meni ik zuc’m lewa e nedoxaqj duyjrtuicd. Oq bi, poi lrubf nbiuy oto, ats az wuh, vai zuqi vyeaxodn ku byoohiw kiv o nuguricl lertxnuutx.
No fayl kuam nqaopopk yijq guqkhouh aof, tug’p lhn o gojqcu qigo lif fx ulcins wse qanciyuzd:
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:
Dco rirfp ul XxusvicxYvasuaj:
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
}
Lgo bapohn eb XekxitoduorBahilg:
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.