Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class MaxSequenceOfEqualElemInArray
- {
- static void Main()
- {
- //Write a program that finds the maximal sequence of equal elements in an array.
- //Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} -> {2, 2, 2}.
- int[] myArray = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
- int counter = 1,
- maxCounter = 1,
- 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.
- int element = myArray[0]; //The element we compare with. It's the first element of the array with index 0.
- //Find the maximal sequence of equal elements in the array
- for (int i = 1; i < myArray.Length; i++) //The cycle starts the comparison from the second memeber of the sequence with index 1.
- {
- if (myArray[i] == element)
- {
- counter++;
- 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.
- {
- maxCounter = counter;
- maxElement = element;
- }
- }
- else
- {
- counter = 1;
- element = myArray[i];
- }
- }
- //Generate the output string, e.g. 2,2,2
- string output = "";
- for (int j = 1; j <= maxCounter; j++)
- {
- if (j != maxCounter)
- {
- output += maxElement + ", ";
- }
- else
- {
- output += maxElement;
- }
- }
- //Print the output string on the console with the correct formatting, e.g. {2,2,2}
- Console.Write("{");
- Console.Write("{0}", output);
- Console.WriteLine("}");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement