Problem-1
Given an array A[0 ...n – 1], where each element of
the array represents a vote in the election. Assume that each vote is given as
an integer representing the ID of the chosen candidate. Write an algorithm (in
pseudo code or in any preferred language, preferably C#) for determining who
wins the election. The
solution should be optimal with respect to time and spece complexity.
e.g. if the array is [3,1, 2, 1, 3, 5, 2, 1,6,8,7,1,1,2,1] the candidate who wins the
election is 1
This answer will help full in Election Counting applicaiton
using System;
using System.Collections.Generic;
using System.Linq;
namespace PracticTest
{
class Program
{
static void Main(string[] args)
{
int[] votesBox = { 3,1, 2, 1, 3, 5, 2, 1,6,8,7,1,1,2,1 };
Practic.CheckVote(votesBox);
}
}
class Practic
{
public static void CheckVote(int[] votesBox)
{
var dict = new Dictionary<int, int>();
// Save votes in Dictionary
foreach (var value in votesBox)
{
if (dict.ContainsKey(value))
{
dict[value]++;
}
else
{
dict[value] = 1;
}
}
foreach (var pair in dict)
{
Console.WriteLine("Candidate {0} got no. of votes :{1}", pair.Key, pair.Value);
}
int maxVoteCount = dict.Values.Max();
int candidateID = dict.First(x => x.Value == dict.Values.Max()).Key;
Console.WriteLine("The candidate {0} has won the election with no. of votes are {1}",candidateID,maxVoteCount);
Console.ReadKey();
}
}
}