Advertisement
vlad0

08.Arrays - 04.MaxSequence

Jan 9th, 2013
49
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. using System.Linq;
  4. using System.Text;
  5.  
  6. //Write a program that finds the maximal sequence
  7. //of equal elements in an array.
  8. //Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1}  {2, 2, 2}.
  9.  
  10.  
  11. namespace _04.SequenceOfEqualElements
  12. {
  13.     class SequenceOfEqualElements
  14.     {
  15.         static void Main(string[] args)
  16.         {
  17.             //note it will find the first Max Sequence for example
  18.             //{ 2, 1, 1, 2, 3, 3, 2, 4, 5, 6, 1 } the max sequence is {1,1}, not {3,3}
  19.  
  20.             int[] myArray = { 1, 1, 3, 4, 5, 6, 7, 8, 9, 7, 7 };
  21.             int counter=1; //initiliaze counter for the sequence
  22.             int maxSeq = 0; //max sequence
  23.             int bestNumber=0; //number with the max sequence
  24.            
  25.             //check till the pre-last element because we compare i == i+1 checks the next element so it will be the last
  26.             for (int i = 0; i < myArray.Length-1; i++)
  27.             {
  28.                 //counter = 1; //the present number by itself is sequence of 1
  29.                 if (myArray[i] == myArray[i+1])
  30.                     {
  31.                         counter++;
  32.                     }
  33.                     else
  34.                     {
  35.                         if (counter > maxSeq)
  36.                         {
  37.                             maxSeq = counter;
  38.                             bestNumber = myArray[i];
  39.                             counter = 1;
  40.                         }
  41.                     }
  42.                 }
  43.            
  44.             //maybe we have to put it in an array but this is shorter :)
  45.             for (int i = 0; i < maxSeq; i++)
  46.             {
  47.                 Console.Write("{0} ", bestNumber);
  48.             }
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement