Advertisement
svetoslavhl

Задача 4

May 21st, 2014
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. //4. Write a program that finds the maximal sequence of equal elements in an array.
  2. //Example: {2, 1, 1, 2, 3, 3, 2,2,2,1} -> {2,2,2}
  3.  
  4.  
  5. using System;
  6.  
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. //We enter the size of the array
  12. Console.WriteLine("Enter the size of the array:");
  13. int size = int.Parse(Console.ReadLine());
  14. int[] arr = new int[size];
  15.  
  16. //We are entering the value of each element of the array
  17.  
  18. for (int i = 0; i < arr.Length; i++)
  19. {
  20.  
  21. Console.Write("arr[{0}] = ", i);
  22. arr[i] = int.Parse(Console.ReadLine());
  23.  
  24.  
  25. }
  26.  
  27.  
  28. //We are copying the array in a new array 1 position bigger
  29.  
  30. int[] arrCopy = new int[size + 1];
  31.  
  32. for (int i = 0; i < arr.Length; i++)
  33. {
  34.  
  35. arrCopy[i] = arr[i];
  36.  
  37.  
  38. }
  39.  
  40. arrCopy[size] = 20; // This means nothing because I wouldn't go to the last value
  41.  
  42.  
  43.  
  44.  
  45. int f = 0;
  46. bool areEqual = true;
  47. int sequence = 0;
  48. int maxSequence = 0;
  49. int firstElemSequence = 0;
  50. do
  51. {
  52. sequence = 0;
  53. do
  54. {
  55. areEqual = arrCopy[f] == arrCopy[f + 1];
  56. f++;
  57. sequence++;
  58.  
  59. } while (areEqual && f < arrCopy.Length - 1);
  60.  
  61. if (sequence > maxSequence)
  62. {
  63. maxSequence = sequence;
  64. firstElemSequence = f - (maxSequence);
  65. }
  66.  
  67. } while (f < arrCopy.Length - 1);
  68.  
  69. //Console.WriteLine("maxSequence = {0}", maxSequence);
  70. //Console.WriteLine("firstElemSequence = {0}", firstElemSequence);
  71.  
  72. //Console.WriteLine("The maximal sequence of equal elements in the array :");
  73. for (int k = 0; k < arrCopy.Length - 1; k++)
  74. {
  75.  
  76. Console.Write("{0}", arrCopy[k]);
  77. if (k != arrCopy.Length - 2)
  78. {
  79. Console.Write(", ");
  80. }
  81.  
  82.  
  83.  
  84.  
  85.  
  86. }
  87.  
  88. Console.Write(" ----> ");
  89.  
  90.  
  91. for (int j = firstElemSequence; j < maxSequence + firstElemSequence; j++)
  92. {
  93.  
  94.  
  95. Console.Write("{0}", arrCopy[j]);
  96. if (j != maxSequence + firstElemSequence - 1)
  97. {
  98. Console.Write(", ");
  99. }
  100.  
  101. }
  102.  
  103. Console.WriteLine();
  104.  
  105.  
  106. }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement