Advertisement
lina94

CountingNumbers'Appearance

Jul 27th, 2013
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. // 4. Write a method that counts how many times given number appears in given array.
  5. // Write a test program to check if the method is working correctly.
  6.  
  7. class CountingNumberInArray
  8. {
  9.     static void Main()
  10.     {
  11.         Console.WriteLine("How many elements do you want to have in the array? ");
  12.         int n = int.Parse(Console.ReadLine());
  13.  
  14.         int[] arrayToCount = new int[n];
  15.  
  16.         // for random generator to fill the array
  17.         Random rndGenerator = new Random();
  18.         for (int i = 0; i < arrayToCount.Length; i++)
  19.         {
  20.             arrayToCount[i] = rndGenerator.Next(1, 100);
  21.         }
  22.  
  23.         // for user input to fill the array
  24.         //for (int i = 0; i < arrayToCount.Length; i++)
  25.         //{
  26.         //    Console.Write("Elemеnt {0} = ", i+1);
  27.         //    arrayToCount[i] = int.Parse(Console.ReadLine());
  28.         //}
  29.  
  30.         Console.WriteLine("Randomly generated array");
  31.         foreach (var number in arrayToCount)
  32.         {
  33.             Console.Write(number + " ");
  34.         }
  35.  
  36.         Dictionary<int, int> dict = CountingNumber(arrayToCount);
  37.  
  38.         Console.WriteLine();
  39.         foreach (var pair in dict)
  40.         {
  41.             Console.WriteLine("The number {0} apears {1} time(s).", pair.Key, pair.Value);
  42.         }
  43.     }
  44.  
  45.     static Dictionary<int, int>  CountingNumber(int[] array)
  46.     {
  47.         var dict = new Dictionary<int, int>();
  48.  
  49.         foreach (int value in array)
  50.         {
  51.             if (dict.ContainsKey(value))
  52.             {
  53.                 dict[value]++;
  54.             }
  55.  
  56.             else
  57.             {
  58.                 dict.Add(value, 1);
  59.             }
  60.         }
  61.         return dict;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement