Recap - Priority Queue
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 41 of 57.
Challenge
MediumBuild a priority queue that works for any prioritized type. Prioritized (with priority) and the data classes Job and Ticket are supplied.
TaskQueue<T : Prioritized>haspush(item),pop()andpeek(), which remove or return the item with the highest priority (the one pushed first among equal priorities) ornull,size,items()(a read-only snapshot in pop order) anddrain(n), which pops up tonitems and returns them as aList<T>.- The generic function
countUrgent(queue, min)takes a queue of any prioritized type and returns how many of its items have at least that priority.
The supplied code reads commands job build 3, ticket 17 5 ada, pop jobs, peek tickets, drain 2 (tickets) or sizes, prints each reply and finally urgent: with the urgent jobs and tickets that are still queued.
Your code goes in TaskQueue.kt, Prioritized.kt, Job.kt and Ticket.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
val jobs = TaskQueue<Job>()
val tickets = TaskQueue<Ticket>()
for (cmd in input) {
val p = cmd.split(" ")
when (p[0]) {
"job" -> jobs.push(Job(p[1], p[2].toInt()))
"ticket" -> tickets.push(Ticket(p[1].toInt(), p[2].toInt(), p[3]))
"pop" -> println("popped " + (if (p[1] == "jobs") jobs.pop() else tickets.pop()))
"peek" -> println("next " + (if (p[1] == "jobs") jobs.peek() else tickets.peek()))
"drain" -> println("drained " + tickets.drain(p[1].toInt()).map { it.customer })
else -> println("jobs ${jobs.size}, tickets ${tickets.size}")
}
}
println("urgent: ${countUrgent(jobs, 4) + countUrgent(tickets, 4)}")
}
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Kotlin playground