Introduction to Practice Problems

Welcome to the practical segment of our C# programming journey! Today, we'll apply the knowledge from past lessons to solve two practice problems using advanced C# data structures: queues, deques, and sorted dictionaries 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 C#.

using System;
using System.Collections.Generic;

class Queue
{
    private LinkedList<string> buffer;

    public Queue()
    {
        // Initializing an empty queue
        buffer = new LinkedList<string>();
    }

    // Adding (enqueueing) an item to the queue
    public void Enqueue(string val)
    {
        buffer.AddLast(val);
    }

    // Removing (dequeuing) an item from the queue
    public string Dequeue()
    {
        if (IsEmpty())
        {
            throw new InvalidOperationException("Queue is empty");
        }
        string value = buffer.First.Value;
        buffer.RemoveFirst();
        return value;
    }

    // Checking if the queue is empty
    public bool IsEmpty()
    {
        return buffer.Count == 0;
    }

    // Checking the size (number of items) in the queue
    public int Size()
    {
        return buffer.Count;
    }

    public static void Main(string[] args)
    {
        Queue restaurantQueue = new Queue();

        restaurantQueue.Enqueue("Order 1");
        restaurantQueue.Enqueue("Order 2");

        Console.WriteLine("Dequeued: " + restaurantQueue.Dequeue());
        Console.WriteLine("Dequeued: " + restaurantQueue.Dequeue());
    }
}

This code demonstrates the creation and operation of a Queue class, which leverages LinkedList<T> 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.

Analyzing the First Problem Solution

We've mimicked a real-world system by implementing a queue using C#'s LinkedList<T>. The enqueuing of an item adheres to the FIFO principle, similar to the action of receiving a new order at the restaurant. The dequeuing serves an order, reflecting the preparation and delivery of the order.

Second Practice Problem: Using Sorted Dictionaries 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 dictionary for easy and efficient access.

using System;
using System.Collections.Generic;

class Player : IComparable<Player>
{
    public string Name { get; }
    public int Score { get; }

    public Player(string name, int score)
    {
        Name = name;
        Score = score;
    }

    public int CompareTo(Player other)
    {
        int scoreComparison = Score.CompareTo(other.Score);
        if (scoreComparison == 0)
        {
            return Name.CompareTo(other.Name);
        }
        return scoreComparison;
    }

    public override bool Equals(object obj)
    {
        if (this == obj) return true;
        if (obj == null || GetType() != obj.GetType()) return false;
        Player player = (Player)obj;
        return Score == player.Score && Name == player.Name;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + Name.GetHashCode();
            hash = hash * 23 + Score.GetHashCode();
            return hash;
        }
    }

    public override string ToString()
    {
        return $"({Name}, {Score})";
    }

    public static void Main(string[] args)
    {
        SortedDictionary<Player, int> scores = new SortedDictionary<Player, int>();

        Player player1 = new Player("John", 900);
        Player player2 = new Player("Doe", 1000);

        // Adding players to the SortedDictionary
        scores[player1] = player1.Score;
        scores[player2] = player2.Score;

        // Print SortedDictionary
        foreach (var entry in scores)
        {
            Console.WriteLine(entry.Key); // e.g., (John, 900)
        }
    }
}

This code snippet introduces a Player class for representing players in a video game, implementing the IComparable<Player> interface to allow sorting by score (primary) and name (secondary). Instances of this class are then used as keys in a SortedDictionary<Player, int>, 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.

Analyzing the Second Problem Solution

In our leaderboard system, we used a Player custom class with comparator methods for sorting. We stored instances of Player in a sorted dictionary with their corresponding scores. The SortedDictionary<Player, int> allows us to access player scores in a sorted order efficiently, a common requirement in a competitive gaming system.

Lesson Summary

We've successfully employed C#'s built-in data structures — queues, deques, and sorted dictionaries — 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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal