Advertisement
d_brezoev

MinRemovesOrdering

Dec 14th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.31 KB | None | 0 0
  1. /* * Write a program that reads an array of integers and removes from it a minimal number of
  2.  * elements in such way that the remaining array is sorted in increasing order.
  3.  * Print the remaining sorted array. Example:
  4.     {6, 1, 4, 3, 0, 3, 6, 4, 5}  {1, 3, 3, 4, 5}
  5.  */
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10.  
  11. namespace _18.SortWithMinRemoves
  12. {
  13.     class SortWithMinRemoves
  14.     {              
  15.         static bool CheckIfOrdered(List<int> arr)
  16.         {
  17.             bool isOrdered = true;
  18.             for (int i = 0; i < arr.Count-1; i++)
  19.             {
  20.                 if (arr[i]>arr[i+1])
  21.                 {
  22.                     isOrdered = false;
  23.                     break;
  24.                 }
  25.             }
  26.             return isOrdered;
  27.  
  28.         }
  29.         static void Main(string[] args)
  30.         {
  31.             int[] arr = { 1,2,3,4,5,6,7,1,123,453,4674};            
  32.             List<int> list = new List<int>(arr.Length);          
  33.             int bitCounter = 0;
  34.             int minRemoves = int.MaxValue;            
  35.             StringBuilder sb = new StringBuilder();            
  36.             int maxRotations = (int)Math.Pow(2, arr.Length) - 1;
  37.             for (int i = 1; i < maxRotations; i++)
  38.             {
  39.                 for (int p = 0; p < arr.Length; p++)
  40.                 {
  41.                     int mask = 1 << p;
  42.                     int m = i & mask;
  43.                     int bit = m >> p;
  44.                     if (bit == 1)
  45.                     {
  46.                         bitCounter++;
  47.                     }
  48.                     else
  49.                     {
  50.                         list.Add(arr[p]);
  51.                     }
  52.                 }
  53.                 bool ordered = CheckIfOrdered(list);
  54.                 if (ordered)
  55.                 {
  56.                     if (bitCounter<minRemoves)
  57.                     {
  58.                         sb.Clear();
  59.                         minRemoves = bitCounter;
  60.                         for (int j = 0; j < list.Count; j++)
  61.                         {
  62.                             sb.Append(list[j] + " ");
  63.                         }
  64.                     }
  65.                 }
  66.                 bitCounter = 0;
  67.                 list.Clear();
  68.             }
  69.             Console.WriteLine(sb);
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement