简体   繁体   English

查找最高票数并匹配字符串数组

[英]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. 我只是开始在家学习C#。

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. 如果您遇到问题,StackOverflow并不是发布问题的网站,仅当您遇到的问题需要可以帮助他人的解决方案时。

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> . 但是,如果您想进行更多事情(例如谁的票数最少)而不进行此类事情,则应该使用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 ) (有关更多信息,请访问: 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: 我不知道您在C#和编程教育方面有多远(OOP之类的东西),因此您可能会发现或发现以下几点:

  • you should use generic collections and not primitive arrays ( List<> in this case). 您应该使用通用集合而不是原始数组(在这种情况下为List<> )。
  • 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 : 您可能应该改用dictionary,但如果要使用array,请按以下步骤操作:

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. 然后使用IndexOf静态方法在数组中查找max的索引。 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 您可以从DotNetPerlsMSDNArray.IndexOf()有一个清晰的概念

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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