Advertisement
sylviapsh

Maximal sequence of equal elements in an array

Jan 9th, 2013
713
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System;
  2. class MaxSequenceOfEqualElemInArray
  3. {
  4.   static void Main()
  5.   {
  6.     //Write a program that finds the maximal sequence of equal elements in an array.
  7.         //Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} -> {2, 2, 2}.
  8.  
  9.     int[] myArray = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
  10.     int counter = 1,
  11.         maxCounter = 1,
  12.         maxElement = myArray[0]; //In case of just one element in the array the first element is the winner, that's why the initial value is the one of the first element.
  13.     int element = myArray[0]; //The element we compare with. It's the first element of the array with index 0.
  14.  
  15.     //Find the maximal sequence of equal elements in the array
  16.     for (int i = 1; i < myArray.Length; i++) //The cycle starts the comparison from the second memeber of the sequence with index 1.
  17.     {
  18.       if (myArray[i] == element)
  19.       {
  20.         counter++;
  21.         if (counter > maxCounter)//Note! If there are 2 or more sequences of equal lenghts by checking with ">" the output will be the first sequence. If we check with ">=" we'll get the last one.
  22.         {
  23.           maxCounter = counter;
  24.           maxElement = element;
  25.         }
  26.       }
  27.       else
  28.        {
  29.         counter = 1;
  30.         element = myArray[i];
  31.       }
  32.     }
  33.  
  34.     //Generate the output string, e.g. 2,2,2
  35.     string output = "";
  36.     for (int j = 1; j <= maxCounter; j++)
  37.             {
  38.         if (j != maxCounter)
  39.         {
  40.           output += maxElement + ", ";
  41.         }
  42.         else
  43.         {
  44.           output += maxElement;
  45.         }
  46.             }
  47.  
  48.     //Print the output string on the console with the correct formatting, e.g. {2,2,2}
  49.     Console.Write("{");
  50.     Console.Write("{0}", output);
  51.     Console.WriteLine("}");
  52.   }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement