【问题标题】:Finding highest number of votes and matching to array of string找到最高票​​数并匹配字符串数组
【发布时间】:2014-12-29 22:43:37
【问题描述】:

我试图弄清楚如何将候选人姓名与候选人选票相匹配,并将最高票数与候选人姓名一起显示。

至于如何匹配我拥有的两个数组。

我知道我错过了一些东西,但是什么?我只是在家里才开始学习 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);
        }
    }
}

【问题讨论】:

  • 问题出在哪里?哪条线?什么不工作?
  • 在头脑中想出解决方案,然后再考虑如何在 C# 中完成它。如果您不知道您脑海中的解决方案,那么它与 C# 没有太大关系;)
  • 你知道最大票数是多少。为什么不循环遍历您的 numOfVotes 数组,并且每次找到等于最大值的条目时,您从 candidateName 数组的相同位置访问成员名称?
  • 哈利,代码本身可以工作,但我希望能够写出候选人姓名和他/她的票数

标签: c#


【解决方案1】:

问题的解决方案是这样的:

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

我不知道您在 C# 和编程教育(OOP 等)方面的进展如何,因此您可能会发现以下几点显而易见:

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

我会这样做:

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

【讨论】:

    【解决方案2】:

    看看这些你可以用头脑思考的事情。 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&lt;string, int&gt;。那是一个与数字相关的字符串,一个与投票相关的名称。

    (更多信息请点击此处:http://www.dotnetperls.com/dictionary

    【讨论】:

      【解决方案3】:

      您应该为此使用Dictionary

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

      【讨论】:

      • 我认为 OPs 的实现更倾向于简单的Dictionary&lt;string, int&gt;
      • 是的,使用var winner = candidates.OrderByDescending(c =&gt; c.Value).First(); Console.WriteLine("Winner is {0} with {1} votes.", winner.Key, winner.Value);,您还可以获得得票最多的候选人。领带处理起来会有点复杂。
      【解决方案4】:

      您的代码运行良好。您正在寻找的是具有最高票数的数组的索引。该索引对于获得最高票数的 candidateName 也很有用。因此,要获得该索引,只需使用从这一行获得的最大值:

      int max = numOfVotes.Max();
      

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

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

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

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

      您可以从DotNetPerlsMSDN 中对 Array.IndexOf() 有一个清晰的概念

      【讨论】:

        【解决方案5】:

        你可能应该使用字典,但如果你想使用数组,这里是如何做到的:

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

        【讨论】:

          猜你喜欢
          • 2014-06-26
          • 2019-06-21
          • 2022-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-02
          • 1970-01-01
          相关资源
          最近更新 更多