Advertisement
sylviapsh

Maximal increasing sequence in an array

Jan 9th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2. class MaxIncreasingSequenceInArray
  3. {
  4.   static void Main()
  5.   {
  6.     //Write a program that finds the maximal increasing sequence in an array. Example: {3, 2, 3, 4, 2, 2, 4} -> {2, 3, 4}.
  7.  
  8.     int[] myArray = { 42, 41, 20, 12, 3, 4 };
  9.  
  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+1)
  19.       {
  20.         counter++;
  21.         element = myArray[i];
  22.         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.
  23.         {
  24.           maxCounter = counter;
  25.           maxElement = myArray[i];
  26.         }
  27.       }
  28.       else
  29.       {
  30.         counter = 1;
  31.         element = myArray[i];
  32.       }
  33.     }
  34.  
  35.     //Generate the output string, e.g. 2,2,2
  36.     string output = "";
  37.     for (int j = 1; j <= maxCounter; j++)
  38.     {
  39.       if (j != maxCounter)
  40.       {
  41.         output += ((maxElement - maxCounter) + j) + ", ";
  42.       }
  43.       else
  44.       {
  45.         output += ((maxElement - maxCounter) + j);
  46.       }
  47.     }
  48.  
  49.     //Print the output string on the console with the correct formatting, e.g. {2,2,2}
  50.     Console.Write("{");
  51.     Console.Write("{0}", output);
  52.     Console.WriteLine("}");
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement