Menu
Coddy logo textTech

Recap - Priority Queue

Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 41 of 57.

challenge icon

Challenge

Medium

Build a priority queue that works for any prioritized type. Prioritized (with priority) and the data classes Job and Ticket are supplied.

  • TaskQueue<T : Prioritized> has push(item), pop() and peek(), which remove or return the item with the highest priority (the one pushed first among equal priorities) or null, size, items() (a read-only snapshot in pop order) and drain(n), which pops up to n items and returns them as a List<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

Practice on your own: Kotlin playground