Venciity

[C#] BOOK Arrays - 10 Задача

Jan 6th, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. /* Write a program that finds the most frequent number in an array.
  2.  * Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} ---> 4 (5 times) */
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10. namespace Exercise_10
  11. {
  12.     class Program
  13.     {
  14.         static void Main(string[] args)
  15.         {
  16.             Console.Write("Enter array length: ");
  17.             int length = int.Parse(Console.ReadLine());
  18.             int[] myArray = new int[length];
  19.  
  20.             //enter array elements
  21.             for (int i = 0; i < length; i++)
  22.             {
  23.                 Console.Write("Number {0} = ",i+1);
  24.                 myArray[i] = int.Parse(Console.ReadLine());
  25.             }
  26.  
  27.             Dictionary<int, int> mostFrequent = new Dictionary<int, int>();
  28.             int bestElement = 0;
  29.             int bestFrequency = int.MinValue;
  30.             for (int i = 0; i < length; i++)
  31.             {
  32.                 int tempValue;
  33.                 if (mostFrequent.TryGetValue(myArray[i] , out tempValue))
  34.                 {
  35.                     mostFrequent[myArray[i]] = tempValue + 1;
  36.  
  37.                 } /* if (mostFrequent.TryGetValue(myArray[i] , out tempValue)) казва :
  38.                    * ако в речника има ключ с име "myArray[i]",
  39.                    * дай ми стойността на ключа в променливата tempValue.*/
  40.                 else
  41.                 {
  42.                     mostFrequent.Add(myArray[i], 1);
  43.                 }
  44.             }
  45.             foreach (var item in mostFrequent)
  46.             {
  47.                 if (item.Value > bestFrequency)
  48.                 {
  49.                     bestElement = item.Key;
  50.                     bestFrequency = item.Value;
  51.                 }
  52.             }
  53.             Console.WriteLine();
  54.             Console.WriteLine("The number {0} shows {1} times.",bestElement,bestFrequency);
  55.         }
  56.     }
  57. }
  58.  
  59. /* sorce :
  60.    1. http://forums.academy.telerik.com/126338/c%23-trygetvalue
  61.  
  62.    2. http://stackoverflow.com/questions/9382681/what-is-more-efficient-dictionary-trygetvalue-or-containskeyitem */
Advertisement
Add Comment
Please, Sign In to add comment