Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that finds the most frequent number in an array.
- * Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} ---> 4 (5 times) */
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Exercise_10
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.Write("Enter array length: ");
- int length = int.Parse(Console.ReadLine());
- int[] myArray = new int[length];
- //enter array elements
- for (int i = 0; i < length; i++)
- {
- Console.Write("Number {0} = ",i+1);
- myArray[i] = int.Parse(Console.ReadLine());
- }
- Dictionary<int, int> mostFrequent = new Dictionary<int, int>();
- int bestElement = 0;
- int bestFrequency = int.MinValue;
- for (int i = 0; i < length; i++)
- {
- int tempValue;
- if (mostFrequent.TryGetValue(myArray[i] , out tempValue))
- {
- mostFrequent[myArray[i]] = tempValue + 1;
- } /* if (mostFrequent.TryGetValue(myArray[i] , out tempValue)) казва :
- * ако в речника има ключ с име "myArray[i]",
- * дай ми стойността на ключа в променливата tempValue.*/
- else
- {
- mostFrequent.Add(myArray[i], 1);
- }
- }
- foreach (var item in mostFrequent)
- {
- if (item.Value > bestFrequency)
- {
- bestElement = item.Key;
- bestFrequency = item.Value;
- }
- }
- Console.WriteLine();
- Console.WriteLine("The number {0} shows {1} times.",bestElement,bestFrequency);
- }
- }
- }
- /* sorce :
- 1. http://forums.academy.telerik.com/126338/c%23-trygetvalue
- 2. http://stackoverflow.com/questions/9382681/what-is-more-efficient-dictionary-trygetvalue-or-containskeyitem */
Advertisement
Add Comment
Please, Sign In to add comment