simeon3000

Resizable Array

Jun 22nd, 2017
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1.             int?[] myArr = new int?[4];
  2.  
  3.             string command = string.Empty;
  4.             int cnt = 0;
  5.  
  6.             while (!command.Equals("end"))
  7.             {
  8.                 command = Console.ReadLine();
  9.  
  10.                 if (command.Contains("push"))
  11.                 {
  12.                     int number = int.Parse(command.Split().Last());
  13.  
  14.                     myArr[cnt] = number;
  15.                     cnt++;
  16.  
  17.                     if (cnt == myArr.Length)
  18.                     {
  19.                         Array.Resize<int?>(ref myArr, myArr.Length * 2);
  20.                     }
  21.                 }
  22.  
  23.                 else if (command.Contains("removeAt"))
  24.                 {
  25.                     int index = int.Parse(command.Split().Last());
  26.  
  27.                     myArr[index] = null;
  28.  
  29.                     for (int i = index; i < myArr.Length - 1; i++)
  30.                     {
  31.                         myArr[i] = myArr[i + 1];
  32.                     }
  33.  
  34.                     cnt--;
  35.                 }
  36.  
  37.                 else if (command.Equals("pop"))
  38.                 {
  39.                     myArr[cnt - 1] = null;
  40.  
  41.                     cnt--;
  42.                 }
  43.  
  44.                 else if (command.Equals("clear"))
  45.                 {
  46.                     for (int i = 0; i < myArr.Length; i++)
  47.                     {
  48.                         myArr[i] = null;
  49.  
  50.                         Array.Resize<int?>(ref myArr, 4);
  51.                     }
  52.  
  53.                     cnt = 0;
  54.                 }
  55.             }
  56.            
  57.             if (myArr[0] == null)
  58.             {
  59.                 Console.WriteLine("empty array");
  60.             }
  61.             else
  62.             {
  63.                 Console.WriteLine(string.Join(" ", myArr));
  64.             }
Advertisement
Add Comment
Please, Sign In to add comment