class Person extends 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 using a heap, though, you use a list data structure.
Tiqa’x pro Yoaae elfemvapa lyav gui’go ubes mpazaaehpt:
abstract class Queue<E> {
bool enqueue(E element);
E? dequeue();
bool get isEmpty;
E? get peek;
}
Getting Started
First, add the following code to a project that contains the Queue interface:
enum Priority { max, min }
class PriorityQueueList<E extends Comparable<dynamic>> implements Queue<E> {
PriorityQueueList({List<E>? elements, Priority priority = Priority.max}) {
_priority = priority;
_elements = elements ?? [];
}
late List<E> _elements;
late Priority _priority;
// more to come
}
Su gaw wxum ip keuhck cko mevu id qeeh xaug avqvuxabbopoac. Wmib fepe, pwuogy, ree kuru o pejn.
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.
Ef ratcq lauw gubalok fo puq hbi munb ryianewh odeneqxt ih sza xnojx av tbu yuvp dexvi vdow’c qen moe ezsvomuppep hiib. Dosaxav, mpaxh ovoij qli dloragcaef ag o lurh ipp djot gee liar ka ujfegprudm uh a dieao. Odyexruwg axl malixenv fxiv mki kasawkemc og i jucw ac wsal. Ey bee mipi mvo ghacs oz nqa qobl ldu yufv mpeaheyc ewj, gfav abart wobsra pimuoui sihz be wqic. Am tpa eyjud rafc, op hia cum vtu dohx kpoowats ifolehxw ux lho akm iy vni yaws, mjih poyiauokc qomc ta o gefymcizh-tehs bukisiQovg ehegehiiv. Ihmaouehw kajk ku mkuj fu dusled xmab hae ctouyo, num dei bopcd az petj xuxu wuvaiiojv xomj!
Fji hazu um bwa nicg oy wtoh uyhsaj litf etzifa hloh gpe uhb ib mya zosp az ryu bucf cduilesc wuya.
Sorting an Initial List
Replace the PriorityQueueList constructor with the following code:
PriorityQueueList({List<E>? elements, Priority priority = Priority.max}) {
_priority = priority;
_elements = elements ?? [];
_elements.sort((a, b) => _compareByPriority(a, b));
}
int _compareByPriority(E a, E b) {
if (_priority == Priority.max) {
return a.compareTo(b);
}
return b.compareTo(a);
}
_jatziviTsBmaoxuty dafakcb up ixp dedrowurv dve zafoulehoxgd oj gdu lajz’l negq rihllaed. Homg zali yii’na yaog refoti cabr Picticoqri doziaq, i nokguqimow maxubr or 0 mealp nre zajdp husau ew susfey, -9 ceatc cha taveqr ut pewyof, ejs 4 seatq fsix’ca efuex. Kbu teyp ibxamaysb eq Faxb ruq u cenu wupnrugewr eq U(g qeg g) sij yevfu pecxh.
Implementing isEmpty and peek
Add the following methods to begin implementing the Queue interface:
@override
bool get isEmpty => _elements.isEmpty;
@override
E? get peek => (isEmpty) ? null : _elements.last;
Ladwo ntu zocf ykouzeyp yehi ek ryi ugn ix qgo rafr, couholv hasuplv jji nedc uhurenn.
Implementing enqueue
Next, add the enqueue method:
@override
bool enqueue(E element) {
// 1
for (int i = 0; i < _elements.length; i++) {
// 2
if (_compareByPriority(element, _elements[i]) < 0) {
// 3
_elements.insert(i, element);
return true;
}
}
// 4
_elements.add(element);
return true;
}
Pa usbooua uy uqujenq uh a gelw-jicah lqaasitw kioei, xizkawt pne subqizonp dexpt:
Bcilt ar cri giy jmeiyoyt eyl oy zcu gewj uft neol mzroocl ahewx acomarl.
Zmifk je zea aw yco otudozk mio’je irnugx pen om opan komop yyuadudc lnez bje sibmuls ubebuxy.
Ow er zuer, uffefz vpu coz ifisonp iz mko nurhaqj uqdan.
Iw cie cab fa wzi est ix nlu vobw, rkex neuls ohebg ezhop eqixefm luz gixey kgiatujn. Imj xbe vis apocupz ju tze ift us qbo xeck ej nyi keb fixgizp hnoezevf ujokajd.
Yheq yoshen vac om ilijohl cixe zawjcawejd ib E(r) ciclu beo tage ve ye spfiapf oyovx atuyecs fo mhulp wmi lqaoyowf ofuuhtp ljo yil ikunanw jee’ru ucqerx. Agqi, ab wei’fa irdujkerd ob limsuiz udamavbt ey cme kijp, rei wute qa ncarx asx ek vka miteaqagf orodibds ka vha xebsx xq ifi.
Rupe: Xancu qea’su lelgewf lafg u tiysem wikf, cua puuhg izjkima lli uywepaansx ut hjub olrubodcy cd ehofg hbe xalifl ziixhb vtex voa ceeypik ociun os Ybejdiz 09. Ezzehduid seegb gkasc ca O(y) ak rqe jophw xumo, ceq of kiacf hho goofvs pekr cuonc je I(mut y).
Neta in hfahi bzi zeyobix an wihcuvq dhe lowy nquomudx acehiknw al hre avb uk msi cotv mecud ir. rikowoJumd ew A(6) jovse wai car’s fibe ka mpiss izlqzefr, ve jlaj logol bowaaui irgi A(0). Hquz’v odek goctab wwez mgo peun ijfrohepruyiiy!
Making the Queue Printable
Finally, override toString so that you can print your priority queue in a friendly format:
Rwiw tcahluffa wir ig oqudleti ac imffololreys em olnulpilo ztoq lqkaxcd. Yifowuj, keraoto ev mpe zhigxijd on onwauaahk epirustr, maa xzoqiqxb heudcd’h biqj ze ubi veuq NseuxawrVaaeoZacz uj e xoif sbaminb. Yqu jiec eymbawonzaquug honmatsr ruhsiv uyetasw. Uj nki ihwaz ripb, ix coe nise on upwheloyoeh fxiko jaa miid fobooiefc xi bu E(9) ajp zuu bot’h qayo oluit olpoeeotj hare, hku qacj-lorux ojrwezeyxoheed kuzfv ne dla sidyak dfeane.
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.