Lesson 5
Implementing and Analyzing Data Structures in Kotlin Practice Problems
Introduction to Practice Problems

Welcome to the practical segment of our Kotlin programming journey! Today, we'll apply the knowledge from past lessons to solve two practice problems using advanced Kotlin data structures: queues, deques, and sorted maps with custom class keys.

First Practice Problem: Implementing Queues with Deques

Consider an event-driven system, like a restaurant. Orders arrive, and they must be handled in the order they were received, following the First In, First Out (FIFO) principle. This principle makes it a perfect scenario for a queue or deque implementation in Kotlin.

Kotlin
1import java.util.ArrayDeque 2 3class Queue { 4 private val buffer = ArrayDeque<String>() 5 6 // Adding (enqueueing) an item to the queue 7 fun enqueue(val: String) { 8 buffer.addLast(val) 9 } 10 11 // Removing (dequeuing) an item from the queue 12 fun dequeue(): String { 13 if (isEmpty()) { 14 throw IllegalStateException("Queue is empty") 15 } 16 return buffer.removeFirst() 17 } 18 19 // Checking if the queue is empty 20 fun isEmpty(): Boolean { 21 return buffer.isEmpty() 22 } 23 24 // Checking the size (number of items) in the queue 25 fun size(): Int { 26 return buffer.size 27 } 28} 29 30fun main() { 31 val restaurantQueue = Queue() 32 33 restaurantQueue.enqueue("Order 1") 34 restaurantQueue.enqueue("Order 2") 35 36 println("Dequeued: ${restaurantQueue.dequeue()}") 37 println("Dequeued: ${restaurantQueue.dequeue()}") 38}

This code demonstrates the creation and operation of a Queue class, which leverages ArrayDeque to efficiently implement a queue. The Queue class includes methods to enqueue (add) an item, dequeue (remove) an item, check if the queue is empty, and return the queue's size. Enqueue operations add an item to the end of the deque (simulating the arrival of a new order), while dequeue operations remove an item from the front (simulating the serving of an order), maintaining the First In, First Out (FIFO) principle.

Second Practice Problem: Using Sorted Maps with Custom Class as a Key

For the second problem, envision a leaderboard for a video game. Players with their scores can be represented as objects of a custom class, then stored in a sorted map for easy and efficient access.

Kotlin
1class Player(val name: String, val score: Int) : Comparable<Player> { 2 override fun compareTo(other: Player): Int { 3 if (this.score == other.score) { 4 return this.name.compareTo(other.name) 5 } 6 return this.score.compareTo(other.score) 7 } 8 9 override fun equals(other: Any?): Boolean { 10 if (this === other) return true 11 if (javaClass != other?.javaClass) return false 12 13 other as Player 14 return score == other.score && name == other.name 15 } 16 17 override fun hashCode(): Int { 18 return (name + score).hashCode() 19 } 20 21 override fun toString(): String { 22 return "($name, $score)" 23 } 24} 25 26fun main() { 27 val scores = sortedMapOf<Player, Int>() 28 29 val player1 = Player("John", 900) 30 val player2 = Player("Doe", 1000) 31 32 // Adding players to the SortedMap 33 scores[player1] = player1.score 34 scores[player2] = player2.score 35 36 // Print SortedMap 37 for (entry in scores.entries) { 38 println(entry.key) // e.g., (John, 900) 39 } 40}

This code snippet introduces a Player class for representing players in a video game, incorporating Kotlin's comparison capabilities to allow sorting by score (primary) and name (secondary). Instances of this class are used as keys in a sortedMap, ensuring that players are stored in a manner that is sorted first by their scores and then by their names if scores are equal. This is essential for functionalities like leaderboards, where players need to be ranked efficiently according to their performance.

Lesson Summary and Practice

We've successfully employed Kotlin's built-in data structures — queues or deques, and sorted maps — to solve real-world problems. This hands-on approach enables us to better understand these concepts. More exercises to cement your understanding are coming up next. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.