On the mood to find some solutions for old C# programming contests, I have decided to take a look at a quite simple problem and to give it a try again. I wanted to come up with a solution using List<int> and I finally succeed.

The problem is quite trivial – you are given a number N. Then for each of the next N lines you are given a new number. At the end you should print the number, which is the most repeated one. If two numbers are repeated the same time, the smaller number should be printed. It looks like this:

First we have a “5”, which means that we should have 5 other values, from which to choose the most repeated number. At the end we get “3”, because 3 is repeated twice and it is smaller than 4, which is also repeated twice.

What have I done?

I have initialized one List and for every number, which is given, I have increased the corresponding position +1. At the end I simply printed the position with the highest number, using “indexOf”. The good thing is that if two positions have the same count, indexOf automatically prints the smaller position.

Furthermore, I have added one line concerning conversion from array to list just to remember how it is done 🙂 It is not needed for the answer.

Pretty much that is all. You may enjoy the code here:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { int N = int.Parse(Console.ReadLine()); int[] temp = new int[N]; List<int> myVotes = temp.ToList(); for (int i = 1; i <= N; i++) { int currentVote = int.Parse(Console.ReadLine()); myVotes[currentVote]++; } int Winner = myVotes.IndexOf(myVotes.Max()); Console.WriteLine(Winner); } } |