Introduction

Welcome back to another exciting session where we learn about enhancing existing functionality without causing regressions. Today, our scenario involves designing a voting system. We'll start with the basic implementation of the voting system and gradually introduce additional elements of complexity.

Starter Task Review

In our initial task, we created a simple voting system in C# with a set of basic functionalities:

  • bool RegisterCandidate(string candidateId): This method is used to add new candidates to our system.
  • bool Vote(long timestamp, string voterId, string candidateId): This method facilitates users casting their votes. Each vote is given a timestamp.
  • int? GetVotes(string candidateId): This method retrieves the total number of votes for a given candidate.
  • List<string> TopNCandidates(int n): We also want to add a leaderboard functionality to our system. This method returns the top n candidates sorted by the number of votes.
Initial Solution Development

Let's jump into the C# code and begin the implementation of our starter task. Here, we use C#'s built-in Dictionary and List as the core of our design. These collections allow us to have dynamic lists keyed based on candidate IDs and voter IDs, which will greatly simplify our design.

using System;
using System.Collections.Generic;
using System.Linq;

public class VotingSystem {
    private Dictionary<string, int> candidates;  // Stores candidate_id as key and votes as value
    private Dictionary<string, VotingHistory> voters;  // Tracks each voter's voting history

    public VotingSystem() {
        this.candidates = new Dictionary<string, int>();  // Initialize candidates dictionary
        this.voters = new Dictionary<string, VotingHistory>();  // Initialize voters dictionary
    }

    public bool RegisterCandidate(string candidateId) {
        if (candidates.ContainsKey(candidateId)) {
            return false;  // Candidate is already registered
        }
        candidates[candidateId] = 0;  // Initialize candidates with 0 votes
        return true;
    }

    public bool Vote(long timestamp, string voterId, string candidateId) {
        if (!candidates.ContainsKey(candidateId)) {
            return false;  // Return false if candidate is not registered
        }
        if (!voters.TryGetValue(voterId, out var voterHistory)) {
            voterHistory = new VotingHistory();
            voters[voterId] = voterHistory;
        }
        voterHistory.Votes.Add(candidateId);  // Record the vote
        voterHistory.Timestamps.Add(timestamp);  // Record the time of the vote
        candidates[candidateId]++;  // Increment vote count for the candidate
        return true;
    }

    public int? GetVotes(string candidateId) {
        return candidates.ContainsKey(candidateId) ? candidates[candidateId] : (int?)null;  // Retrieve vote count for a candidate or null if not found
    }

    public List<string> TopNCandidates(int n) {
        return candidates.OrderByDescending(entry => entry.Value)
                         .Take(n)
                         .Select(entry => entry.Key)
                         .ToList();  // Return top n candidates based on votes
    }

    private class VotingHistory {
        public List<string> Votes { get; }
        public List<long> Timestamps { get; }

        public VotingHistory() {
            this.Votes = new List<string>();
            this.Timestamps = new List<long>();
        }
    }
}
Introduce New Methods

Now that we have a basic voting system, our goal is to enhance this system with additional functionalities:

  • Dictionary<string, int> GetVotingHistory(string voterId):: Provides a detailed voting history for a specified voter, returning a dictionary with candidates and the number of votes they received from the voter. Returns null if the voter ID does not exist.
  • bool BlockVoterRegistration(long timestamp):: Implements a mechanism to halt any new voter registrations past a specified timestamp, effectively freezing the voter list as of that moment.
  • bool ChangeVote(long timestamp, string voterId, string oldCandidateId, string newCandidateId):: Enables voters to change their vote from one candidate to another, given the change is made within a 24-hour window from their last vote, ensuring both the old and new candidates are registered, and that the voter initially voted for the old candidate.
Implementing New Methods: 'getVotingHistory' and 'blockVoterRegistration'

We proceed to enhance our existing VotingSystem class to accommodate the new functionalities.

First, let's incorporate the methods to get the voting history and to block further voter registrations:

    private long? blockTime;

    public Dictionary<string, int> GetVotingHistory(string voterId) {
        if (!voters.ContainsKey(voterId)) {
            return null;
        }
        var voterHistory = voters[voterId];
        var votingHistory = new Dictionary<string, int>();

        foreach (var candidateId in voterHistory.Votes) {
            if (!votingHistory.ContainsKey(candidateId)) {
                votingHistory[candidateId] = 0;
            }
            votingHistory[candidateId]++;
        }
        return votingHistory;  // Returns a dictionary with each candidate voted for and the number of times they were voted for
    }

    public bool BlockVoterRegistration(long timestamp) {
        blockTime = timestamp;  // Records the timestamp after which no registration is allowed
        return true;
    }
Updating the 'vote' Method

With the introduction of the BlockVoterRegistration functionality, we must revisit our Vote method to ensure it respects the new rules set by this feature. Specifically, we need to ensure that no votes are cast after the voter registration has been blocked. This is critical in maintaining the integrity of the voting system, especially in scenarios where registration deadlines are enforced. Here's how we modify the Vote method to incorporate this change:

    public bool Vote(long timestamp, string voterId, string candidateId) {
        // Check if blockTime is set and if the vote attempt is after the block timestamp
        if (blockTime.HasValue && timestamp >= blockTime.Value) {
            return false;  // Vote attempt is blocked due to the registration freeze
        }
        
        if (!candidates.ContainsKey(candidateId)) {
            return false;  // Return false if the candidate is not registered
        }
        
        if (!voters.TryGetValue(voterId, out var voterHistory)) {
            voterHistory = new VotingHistory();
            voters[voterId] = voterHistory;
        }
        
        voterHistory.Votes.Add(candidateId);  // Record the vote
        voterHistory.Timestamps.Add(timestamp);  // Record the time of the vote
        candidates[candidateId]++;  // Increment vote count for the candidate
        
        return true;
    }

This update ensures that our voting system behaves as expected, even with the new functionality to block further voter registrations beyond a certain timestamp. It's a perfect demonstration of how new features can necessitate revisits and revisions to existing code to enhance functionality while ensuring backward compatibility.

Implementing 'changeVote' Method

The ChangeVote method allows voters to change their vote, adhering to specific rules. Here's a step-by-step explanation of implementing this functionality:

  • Verify Candidate and Voter Validity: Check if both the old and new candidate IDs exist in the system, and verify that the voter has previously voted for the old candidate.

  • Timestamp Constraints: Ensure that the voter is trying to change their vote within an allowable timeframe after their initial vote.

  • Update Votes: If all conditions are met, subtract one vote from the old candidate, add one vote to the new candidate, and update the voter's voting record.

    public bool ChangeVote(long timestamp, string voterId, string oldCandidateId, string newCandidateId) {
        // Verify existence in the voting system
        if (!candidates.ContainsKey(oldCandidateId) || !candidates.ContainsKey(newCandidateId)) {
            return false;
        }

        // Check if the voter_id is valid and has previously voted
        if (!voters.ContainsKey(voterId) || !voters[voterId].Votes.Any()) {
            return false;  // Voter is either not registered or has not voted yet
        }

        var voterHistory = voters[voterId];
        // Confirm voter has voted for the old candidate
        var lastVoteIndex = voterHistory.Votes.LastIndexOf(oldCandidateId);
        if (lastVoteIndex == -1) {
            return false;
        }

        // Ensure the operation is within the permitted timeframe
        if (timestamp - voterHistory.Timestamps[lastVoteIndex] > 86400) {  // 24 hours in seconds
            return false;
        }

        // Perform the vote change
        // Remove the old vote
        voterHistory.Votes.RemoveAt(lastVoteIndex);
        voterHistory.Timestamps.RemoveAt(lastVoteIndex);
        
        // Append the new vote
        voterHistory.Votes.Add(newCandidateId);
        voterHistory.Timestamps.Add(timestamp);

        // Update candidates' vote counts
        candidates[oldCandidateId]--;
        candidates[newCandidateId]++;

        return true;
    }
Lesson Summary

Congratulations! You've successfully enhanced the voting system by adding functionalities to view voting history, block new candidate registrations, and, most importantly, enable vote changes under specific conditions. Each of these features was developed with careful consideration to maintain the integrity and backward compatibility of the system. Continue exploring with practice sessions and further experimentation to refine your skills in developing complex, functionality-rich applications. 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