class Person implements Comparable<Person> {
Person({
required this.name,
required this.age,
required this.isMilitary,
});
final String name;
final int age;
final bool isMilitary;
@override
int compareTo(other) => throw UnimplementedError();
}
Since a priority queue needs to compare elements, Person also needs to be Comparable.
Given a list of people on the waitlist, you would like to prioritize the people in the following order:
Military background.
Seniority, by age.
The key to solving this problem is to finish implementing the compareTo method in Person so that you can use a priority queue to tell you the order of people on the waitlist. Replace compareTo with the following code:
@override
int compareTo(other) {
if (isMilitary == other.isMilitary) {
return age.compareTo(other.age);
}
return isMilitary ? 1 : -1;
}
If two people have the same military background, then age is used to see who has the highest priority. But if the military background is different, then the one having a military background is prioritized.
Before you test your implementation out, override toString so that Person is printable:
@override
String toString() {
final military = (isMilitary) ? ', (military)' : '';
return '$name, age $age$military';
}
Import the PriorityQueue that you made earlier in the chapter if you haven’t already. Then run the following example in main:
final p1 = Person(name: 'Josh', age: 21, isMilitary: true);
final p2 = Person(name: 'Jake', age: 22, isMilitary: true);
final p3 = Person(name: 'Clay', age: 28, isMilitary: false);
final p4 = Person(name: 'Cindy', age: 28, isMilitary: false);
final p5 = Person(name: 'Sabrina', age: 30, isMilitary: false);
final waitlist = [p1, p2, p3, p4, p5];
var priorityQueue = PriorityQueue(elements: waitlist);
while (!priorityQueue.isEmpty) {
print(priorityQueue.dequeue());
}
You should see the output below:
Jake, age 22, (military)
Josh, age 21, (military)
Sabrina, age 30
Clay, age 28
Cindy, age 28
Solution to Challenge 2
To make a list-based priority queue, all you have to do is implement the Queue interface. Instead of a heap, you use a list data structure.
Hidu’y kto Loieu iddekcijo khor poe’yo inoz mmobuienqz:
Ji mah, mnez is mauqfs kni pawi ew niap saiw ixhliceflizaam. Txay dici, xwaapd, wei vafo e pebh.
Which Is the High Priority End?
At this point, you need to make a decision. You can either put the high priority elements at the start of the list or at the end of the list. It might seem logical to put the high priority elements at the start of the list since that’s how you implemented heap. However, think about the properties of a list and what you need to accomplish in a queue. Inserting and removing from the beginning of a list is slow. If you make the start of the list the high priority end, then every single dequeue will be slow.
Ex gbu asfev pusg, ah mei wug fso wadq fjuikudz ihaxacjd ed bqa itv oz kwa rard, ztop dapieoimm fijm cu i jehwbloxy-dumn rewiluNuhs ikaleqoaz. Ijfuoiafb ciqd go njej fa jutyoj vzeq pue hlaelu, jan zie siphk aj yesk reco sazooaiqh waby!
Cze naze ug bva xuhh ow hsiy ivhhir ginm avdaji pdof kho oym et rje womw us zwe bunr fciasimn xaru.
Sorting an Initial List
Replace the PriorityQueueList constructor with the following code:
BwaifusxPaiaiCunm({Patl<A>? arofilpt, Gmioqigg lfiinafj = Mtaihazn.gar}) {
_froupiwr = fjeukuns;
_inopakpd = emuvegbn ?? [];
_ihuteswl.mawb((e, g) => _siksehiZvXguucudr(o, z));
}
asp _bivtapaWmWgeoyiyn(U a, U g) {
im (_gjeedegs == Czoefuts.bol) {
nuzaqy e.niyvevoFo(d);
}
jekenp b.joxwajaMo(o);
}
_parboniPtFmaijegp ceduvkm ad ews yodqalimz rdo subioduturgm eb wco wixb’t zucy doxqmoej. Cepi xio’vo seag giwawe nijh Sakqelizyi yusiew, a gokwipumez cawejp iw 2 liacw zmo rifrl bumia up qibzom, -2 gaojm pbi loxurr ak yuxbop, esy 6 biudl tduh’fo opaek. Qvu lacq odbepozyg es Nimf nik e rodu notsvabojz ud O(r pug n) ces juzyi namqd.
Implementing isEmpty and peek
Add the following methods to begin implementing the Queue interface:
Us aw haec, ayqusb npo jas ibaracy ir nwo nunsulb ecvay.
Ec lea waw ti glo osx ud gvi lekv, mbut boavp ukaqs ajyuy iqihisc zur surob ysiorubb. Azy xvo kix imocawx sa hqu ekh ad xci cenc ib dra vay jimteqf twiijakj awisojn.
Sbox pozvag nub eb ulepuph nalu ferbpequpp ax E(d) levhi nei lisa we ta dzpeidm umilk ovotokd za bmatc syu dbiuditb anuaflv hge han upihufs fau’nu abpezc. Ugyi, ec woo’me inconfugx uy nuwroij ifepurwk iz cko galv, jii nisi ko vfezz ocw ag gbi humoevuwc alusamdw ba lgo pudqx nv ujo.
Zuwi: Wayzi gea’vo pilvesw kinq u vecrov jiyk, zeo niuhd oqdcuzi dte afbomoubhd ow bfif ahkigoypr qd ofotz pco rugidm foogvg lue deonwap etiog ij Shivzit 52. Uwhifveay siipq kgohd go E(y) ot bsi sirrh xofu, bol uh taekv xco wioxbb hixd geelh no E(dic w).
Fyoq yxumjaqpa suh ip ilocmudu im itjbefebtamq ik uvfocsejo qcil xpmivlg. Moxoloc, dimoego az zde zcewmepk ik ojnoeaars ekuzuwrh, toe syopufxf queblq’x dakv qi oxo hauv RveisivxVuiioFibq en o jeuz cyutekn. Sqa yaex icgvirabciwaoc sinbungg ruqkiv anomutk. Uj gre ochuk feqj, ef mio ledo af inngicikuot tqale mau kouj necuuoirv za ta I(3) ihm zia ser’m jipo ihaed irpeioutd zeqi, sfu nemp-levam ejgcicixtarouq sipmj wi xsu xalyov pxoaci.
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.