繁体   English   中英

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

[英]Finding highest number of votes and matching to array of string

我试图弄清楚如何将候选人名称与候选人投票相匹配,并显示最高的投票和候选人姓名。

就像我如何匹配两个数组一样。

我知道我想念什么,但是呢? 我只是开始在家学习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);
        }
    }
}

您应该为此使用字典

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));
}

看到这些想法,您可以脑海中思考。 如果您遇到问题,StackOverflow并不是发布问题的网站,仅当您遇到的问题需要可以帮助他人的解决方案时。

这将起作用(对我来说最直接的方法):

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);

但是,如果您想进行更多事情(例如谁的票数最少)而不进行此类事情,则应该使用Dictionary<string, int> 那是一个与数字关联的字符串,一个与投票关联的名称。

(有关更多信息,请访问: http : //www.dotnetperls.com/dictionary

解决该问题的方法是,执行以下操作:

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

我不知道您在C#和编程教育方面有多远(OOP之类的东西),因此您可能会发现或发现以下几点:

  • 您应该使用通用集合而不是原始数组(在这种情况下为List<> )。
  • 您应该将所有这些封装到一个类中。

这就是我要做的:

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;
    }
}

您可能应该改用dictionary,但如果要使用array,请按以下步骤操作:

avgMarks = numOfVotes.Average();

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

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

您的代码运行正常。 您正在寻找的是具有最高投票数的数组的索引。 该索引对于获得最高投票数的候选人名称也很有用。 因此,要获取该索引,只需使用从此行获得的最大值:

int max = numOfVotes.Max();

然后使用IndexOf静态方法在数组中查找max的索引。 为此,请尝试以下代码行:

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

现在只需打印出候选人姓名和最高投票数,如下所示:

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

您可以从DotNetPerlsMSDNArray.IndexOf()有一个清晰的概念

暂无
暂无

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

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