sashomaga

Increasing order

Jan 7th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. //Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the
  5. //remaining array is sorted in increasing order. Print the remaining sorted array.
  6. //Example: {6, 1, 4, 3, 0, 3, 6, 4, 5} => {1, 3, 3, 4, 5}
  7.  
  8. class Program
  9. {
  10.     static void Main()
  11.     {
  12.         int[] myArray = {6, 1, 4, 3, 0, 3, 6, 4, 5};
  13.         StringBuilder builder = new StringBuilder();
  14.  
  15.         string bestSubset = "";
  16.         int bestCount = 0;
  17.         string currentSubset = "";
  18.         int currentCount = 0;
  19.         int test = 0;
  20.         int subsetCount = (int)Math.Pow(2, myArray.Length);
  21.  
  22.         for (int i = 1; i <= subsetCount; i++)
  23.         {
  24.                 if (currentCount > bestCount)
  25.                 {
  26.                     bestCount = currentCount;
  27.                     bestSubset = currentSubset;
  28.                 }
  29.                 currentSubset = "";
  30.                 currentCount = 0;
  31.                 builder.Clear();
  32.  
  33.             for (int j = 0; j < myArray.Length; j++)
  34.             {
  35.                
  36.                 if ((i >> j & 1) == 1)
  37.                 {                                        
  38.                     if (currentSubset == "")
  39.                     {
  40.                         test = myArray[j];
  41.                         builder.Append(myArray[j]);
  42.                         currentSubset = builder.ToString();
  43.                         currentCount++;                  
  44.                     }
  45.                     else if (test <= myArray[j])
  46.                     {
  47.                         builder.Append(",").Append(myArray[j]);
  48.                         currentSubset = builder.ToString();
  49.                         currentCount++;
  50.                     }
  51.                     else
  52.                     {
  53.                         continue;
  54.                     }
  55.                     test = myArray[j];
  56.                 }
  57.  
  58.             }
  59.            
  60.         }
  61.         Console.WriteLine("Remining sorted array:({0})", bestSubset);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment