Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace ResizablArray
- {
- using System;
- using System.Linq;
- using System.Text;
- public class ResizablArray
- {
- public static int currentSizeOfArray = 4;
- public static int currIndexOfElement = 0;
- public static int[] array = new int[4];
- public static void Main()
- {
- string inputLine = ReadInputFromConsole();
- while (inputLine != "end")
- {
- string[] commandInfo = inputLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- switch (commandInfo[0])
- {
- case "push":
- int number = int.Parse(commandInfo[1]);
- PushElementInTheEndOfTheArray(number);
- break;
- case "pop":
- RemoveElementAtIndex(array.Length - 1);
- break;
- case "removeat":
- int index = int.Parse(commandInfo[1]);
- RemoveElementAtIndex(index);
- break;
- case "clear":
- ClearTheArray();
- break;
- default:
- break;
- }
- inputLine = ReadInputFromConsole();
- }
- PrintTheElements();
- }
- private static void PrintTheElements()
- {
- StringBuilder result = new StringBuilder();
- if (currIndexOfElement == 0)
- {
- result.Append("empty array");
- goto Print;
- }
- for (int currElement = 0; currElement < currIndexOfElement; currElement++)
- {
- result.Append(array[currElement]);
- if (currElement + 1 != currIndexOfElement)
- {
- result.Append(" ");
- }
- }
- Print:
- Console.WriteLine(result.ToString());
- }
- private static void ClearTheArray()
- {
- currentSizeOfArray = 4;
- currIndexOfElement = 0;
- array = new int[currentSizeOfArray];
- }
- private static void RemoveElementAtIndex(int index)
- {
- if (array.Length == 0 || index < 0 || index >= array.Length)
- {
- return;
- }
- for (int currElement = index; currElement < array.Length - 1; currElement++)
- {
- array[currElement] = array[currElement + 1];
- }
- array[array.Length - 1] = 0;
- currIndexOfElement--;
- }
- private static void PushElementInTheEndOfTheArray(int numberToAdd)
- {
- if (currIndexOfElement == array.Length)
- {
- DoubleUpTheSizeOfTheArray();
- }
- array[currIndexOfElement] = numberToAdd;
- currIndexOfElement++;
- }
- private static void DoubleUpTheSizeOfTheArray()
- {
- int[] arrayHolder = array.ToArray();
- currentSizeOfArray *= 2;
- array = new int[currentSizeOfArray];
- for (int currElement = 0; currElement < arrayHolder.Length; currElement++)
- {
- array[currElement] = arrayHolder[currElement];
- }
- }
- private static string ReadInputFromConsole()
- {
- return Console.ReadLine().Trim().ToLower();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement