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 Go with a set of basic functionalities:

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

Let's jump into the Go code and begin the implementation of our starter task. Here, we use Go's built-in map and slice 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.

package main

import (
    "sort"
)

type VotingSystem struct {
    candidates map[string]int
    voters     map[string]*VotingHistory
}

type VotingHistory struct {
    Votes      []string
    Timestamps []int64
}

func NewVotingSystem() *VotingSystem {
    return &VotingSystem{
        candidates: make(map[string]int),
        voters:     make(map[string]*VotingHistory),
    }
}

func (vs *VotingSystem) RegisterCandidate(candidateId string) bool {
    if _, exists := vs.candidates[candidateId]; exists {
        return false // Candidate is already registered
    }
    vs.candidates[candidateId] = 0 // Initialize candidates with 0 votes
    return true
}

func (vs *VotingSystem) Vote(timestamp int64, voterId string, candidateId string) bool {
    if _, exists := vs.candidates[candidateId]; !exists {
        return false // Return false if the candidate is not registered
    }
    voterHistory, exists := vs.voters[voterId]
    if !exists {
        voterHistory = &VotingHistory{}
        vs.voters[voterId] = voterHistory
    }
    voterHistory.Votes = append(voterHistory.Votes, candidateId)
    voterHistory.Timestamps = append(voterHistory.Timestamps, timestamp)
    vs.candidates[candidateId]++
    return true
}

func (vs *VotingSystem) GetVotes(candidateId string) *int {
    if votes, exists := vs.candidates[candidateId]; exists {
        return &votes
    }
    return nil
}

func (vs *VotingSystem) TopNCandidates(n int) []string {
    type candidateVote struct {
        id    string
        votes int
    }

    var candidateList []candidateVote
    for id, votes := range vs.candidates {
        candidateList = append(candidateList, candidateVote{id, votes})
    }

    sort.Slice(candidateList, func(i, j int) bool {
        return candidateList[i].votes > candidateList[j].votes
    })

    var topCandidates []string
    for i := 0; i < n && i < len(candidateList); i++ {
        topCandidates = append(topCandidates, candidateList[i].id)
    }
    return topCandidates
}
Introduce New Methods

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

  • func GetVotingHistory(voterId string) map[string]int: Provides a detailed voting history for a specified voter, returning a map with candidates and the number of votes they received from the voter. Returns nil if the voter ID does not exist.
  • func BlockVoterRegistration(timestamp int64) bool: Implements a mechanism to halt any new voter registrations past a specified timestamp, effectively freezing the voter list as of that moment.
  • func ChangeVote(timestamp int64, voterId string, oldCandidateId string, newCandidateId string) bool: 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 the getVotingHistory Method

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

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

var blockTime *int64

func (vs *VotingSystem) GetVotingHistory(voterId string) map[string]int {
    voterHistory, exists := vs.voters[voterId]
    if !exists {
        return nil
    }
    votingHistory := make(map[string]int)
    for _, candidateId := range voterHistory.Votes {
        votingHistory[candidateId]++
    }
    return votingHistory
}

func (vs *VotingSystem) BlockVoterRegistration(timestamp int64) bool {
    blockTime = &timestamp
    return true
}
Updating the vote Method

With the introduction of the BlockVoterRegistration functionality, we must revisit our Vote function 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 function to incorporate this change:

func (vs *VotingSystem) Vote(timestamp int64, voterId string, candidateId string) bool {
    if blockTime != nil && timestamp >= *blockTime {
        return false // Vote attempt is blocked due to the registration freeze
    }

    if _, exists := vs.candidates[candidateId]; !exists {
        return false // Return false if the candidate is not registered
    }

    voterHistory, exists := vs.voters[voterId]
    if !exists {
        voterHistory = &VotingHistory{}
        vs.voters[voterId] = voterHistory
    }

    voterHistory.Votes = append(voterHistory.Votes, candidateId)
    voterHistory.Timestamps = append(voterHistory.Timestamps, timestamp)
    vs.candidates[candidateId]++

    return true
}
Implementing changeVote Method

The ChangeVote function 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.

func (vs *VotingSystem) ChangeVote(timestamp int64, voterId string, oldCandidateId string, newCandidateId string) bool {
    if blockTime != nil && timestamp >= *blockTime {
        return false // Vote change attempt is blocked due to the registration freeze
    }

    if _, exists := vs.candidates[oldCandidateId]; !exists {
        return false // Old candidate is not registered
    }

    if _, exists := vs.candidates[newCandidateId]; !exists {
        return false // New candidate is not registered
    }

    voterHistory, exists := vs.voters[voterId]
    if !exists || len(voterHistory.Votes) == 0 {
        return false // Voter is either not registered or has not voted yet
    }

    lastVoteIndex := -1
    for i, candidate := range voterHistory.Votes {
        if candidate == oldCandidateId {
            lastVoteIndex = i
        }
    }
    if lastVoteIndex == -1 {
        return false // Voter has not voted for the old candidate
    }

    if timestamp-voterHistory.Timestamps[lastVoteIndex] > 86400 {
        return false // Vote change exceeds the 24-hour window
    }

    voterHistory.Votes[lastVoteIndex] = newCandidateId
    voterHistory.Timestamps[lastVoteIndex] = timestamp

    vs.candidates[oldCandidateId]--
    vs.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