简体   繁体   中英

Finding highest number of votes and matching to array of string

I'm trying to figure out how to match a candidate name with candidate votes and display the highest vote along with the candidate name.

As in how to match the two arrays I have.

I know I'm missing something but what? I've only started learing C# at home.

namespace NumberOfVotes
{
    class Program
    {
        static void Main(string[] args)
        {
            int size, minVotes;
            int[] numOfCandidates;
            int[] numOfVotes;
            double avgMarks;

            string[] candidateName;

            Console.WriteLine("Enter number of candidates");
            size = int.Parse(Console.ReadLine());

            numOfCandidates = new int[size];
            candidateName = new string[size];
            numOfVotes = new int[size];

            for (int i = 0; i < numOfCandidates.Length; i++)
            {
                Console.WriteLine("Enter a Candidate Name");
                candidateName[i] = Console.ReadLine();

                Console.WriteLine("Enter number of votes thus far");
                numOfVotes[i] = int.Parse(Console.ReadLine());
            }

            int max = numOfVotes.Max();          
            avgMarks = numOfVotes.Average();
            minVotes = numOfVotes.Min();

            Console.WriteLine("Average votes: {0}", avgMarks);
            Console.WriteLine("Min number of votes is: {0}", minVotes);
        }
    }
}

You should use a Dictionary for this:

static void Main(string[] args)
{
    var candidates = new Dictionary<string, int>();
    Console.WriteLine("Enter number of candidates");
    var size = int.Parse(Console.ReadLine());

    for (int i = 0; i < size; i++)
    {
        Console.WriteLine("Enter a Candidate Name");
        var name = Console.ReadLine();

        Console.WriteLine("Enter number of votes thus far");
        var votes = int.Parse(Console.ReadLine());

        candidates.Add(name, votes);
    }

    Console.WriteLine("Average votes: {0}", candidates.Average(entry => entry.Value));
    Console.WriteLine("Min number of votes is: {0}", candidates.Min(entry => entry.Value));
}

See these kind of things you can do with thinking about it with your head. StackOverflow isn't a website to post your problem if you're stuck, only if the problem you have needs a solution which can help other people.

This would work(most straightfoward approach to me):

int maxIndex = -1;
int max = -1;

for (int i = 0; i < numOfCandidates.Length; i++)
{
    Console.WriteLine("Enter a Candidate Name");
    candidateName[i] = Console.ReadLine();

    Console.WriteLine("Enter number of votes thus far");
    int num = int.Parse(Console.ReadLine()); // <-- unsafe

    // just check it every time, if the number is greater than the previous maximum, update it.
    if (num > max)
    {
       max = num;
       maxIndex = i;
    }

    numOfVotes[i] = num;
}

Console.WriteLine("Candidate {0}, with {1} votes, has the most votes", candidateName[maxIndex], max);

However, if you want more things to calculate (like who has the least votes) without doing these kind of things, you should use a Dictionary<string, int> . That's a string associated with a number, a name associated with votes.

(More info about that here: http://www.dotnetperls.com/dictionary )

The solution to the problem, as it is, is to do something like this:

int indexOfWinner = Array.IndexOf(numOfVotes, numOfVotes.Max());
string winner = candidateName[indexOfWinner];

I don't know how far along in your C# and programming education you are (OOP and suchlike), so a couple of points you may find obvious or not:

  • you should use generic collections and not primitive arrays ( List<> in this case).
  • you should encapsulate all this into a class.

This is how I would do it:

class Program
{
    static void Main(string[] args) {
        Candidates c = new Candidates("foo", "bar", "baz");
        Random rand = new Random();
        c.addVote(0, rand.Next(100));
        c.addVote(1, rand.Next(100));
        c.addVote(2, rand.Next(100));

        Console.WriteLine(c.getWinner());

        Console.WriteLine("number of votes:");
        Console.WriteLine(c[0] + ": " + c[0].numberOfVotes);
        Console.WriteLine(c[1] + ": " + c[1].numberOfVotes);
        Console.WriteLine(c[2] + ": " + c[2].numberOfVotes);
    }
}

class Candidates
{
    private List<Candidate> candidates;

    public Candidate this[string name] {
        get {
            return candidates.First(v => v.name == name);
        }
    }
    public Candidate this[int index] {
        get {
            return candidates[index];
        }
    }

    public Candidates(string firstCandidate, params string[] candidates) { //this is done to disable an empty constructor call
                                                                           //and also allow multiple candidates
        this.candidates = new List<Candidate>(candidates.Length);
        this.candidates.Add(new Candidate(firstCandidate));
        foreach(var c in candidates) {
            this.candidates.Add(new Candidate(c));
        }
    }

    public void addVote(int candidateNumber, int numberOfVotes = 1) {
        candidates[candidateNumber].numberOfVotes += numberOfVotes;
    }

    public Candidate getWinner() {
        candidates.Sort((candidate1, candidate2) => candidate2.numberOfVotes.CompareTo(candidate1.numberOfVotes));
        return candidates[0];
    }
}

class Candidate
{
    public string name { get; private set; }
    public int numberOfVotes { get; set; }

    public Candidate(string name) {
        this.name = name;
        this.numberOfVotes = 0;
    }

    public override string ToString() {
        return name;
    }
}

You should probably use dictionary instead, but if you want to use array, here's how to do it :

avgMarks = numOfVotes.Average();

int avgIndex = numOfVotes.ToList().IndexOf(avgMarks);

Console.WriteLine("Average votes: {0} Candidate Names: {1}", avgMarks, candidateName[avgIndex]);

Your code just works fine. What you are looking for is the index of the array having highest number of votes. This index will be also useful to get the candidateName having highest number of vote. So, to get that index simply use the maximum value you got from this line :

int max = numOfVotes.Max();

and then use IndexOf static method to find the index of max in your array. For that try this line of code :

int index = Array.IndexOf<int>(numOfVotes, max);

Now simply print out the candidateName and highest number of votes as below :

Console.WriteLine(candidateName[index] + " has highest number of vote : " + numOfVotes[index] );

You can have a clean conception about Array.IndexOf() from DotNetPerls and MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM