Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //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}.
- using System;
- using System.Collections.Generic;
- class MaximalSequence
- {
- static void Main()
- {
- uint arrayLength;
- int currentLength = 1;
- int maxLength = 0;
- List<int> elements = new List<int>();
- Console.Write("Enter the array's length: ");
- while (!uint.TryParse(Console.ReadLine(), out arrayLength) || arrayLength == 0)
- {
- Console.Write("Invalid input. Enter a positive integer number: ");
- }
- int[] array = new int[arrayLength];
- for (int i = 0; i < arrayLength; i++)
- {
- Console.Write("Enter the {0} element of the array: ", i);
- while (!int.TryParse(Console.ReadLine(), out array[i]))
- {
- Console.Write("Invalid input. Enter an integer number: ");
- }
- }
- int pointer = array[0];
- for (int i = 1; i < arrayLength; i++)
- {
- if (pointer == array[i])
- {
- currentLength++;
- }
- else
- {
- pointer = array[i];
- if (maxLength < currentLength)
- {
- maxLength = currentLength;
- elements.Clear();
- elements.Add(array[i - 1]);
- }
- else if (maxLength == currentLength)
- {
- elements.Add(array[i - 1]);
- }
- currentLength = 1;
- }
- }
- if (maxLength < currentLength)
- {
- maxLength = currentLength;
- elements.Clear();
- elements.Add(array[arrayLength - 1]);
- }
- else if (maxLength == currentLength)
- {
- elements.Add(array[arrayLength - 1]);
- }
- if (elements.Count == 1)
- {
- Console.Write("There is one sequence with maximal length: ");
- }
- else
- {
- Console.WriteLine("There are {0} sequences with maximal length: ", elements.Count);
- }
- foreach (var element in elements)
- {
- int[] maxSequence = new int[maxLength];
- for (int i = 0; i < maxLength; i++)
- {
- maxSequence[i] = element;
- }
- Console.WriteLine(string.Join(", ", maxSequence));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement