Created
February 16, 2022 15:07
-
-
Save Lvcios/019731ff1635d50c9f68b9e9b8473168 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| namespace DataStructures.CustomArray | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| Console.WriteLine("Hello Custom Array!"); | |
| var myCustomArray = new CustomArray(100); | |
| myCustomArray.Push(2);//position 0 | |
| myCustomArray.Push(4);//position 1 | |
| myCustomArray.Push(6);//position 2 | |
| myCustomArray.Push(8);//position 3 | |
| myCustomArray.Push(10);//position 4 | |
| myCustomArray.PrintArray(); | |
| myCustomArray.Pop(); | |
| myCustomArray.Pop(); | |
| myCustomArray.PrintArray(); | |
| myCustomArray.Push(7);//position 3 | |
| myCustomArray.Push(9);//position 4 | |
| myCustomArray.Push(11);//position 5 | |
| myCustomArray.PrintArray(); | |
| myCustomArray.Remove(3); //it will remove item in position 3, at this point it is the "7" | |
| myCustomArray.PrintArray();//Now items in position 4 and 5 changes their position in arrays to 3 and 4 | |
| var myCustomArrayMemoExcep = new CustomArray(10); | |
| myCustomArrayMemoExcep.Push("myItem1"); | |
| myCustomArrayMemoExcep.PrintArray(); | |
| myCustomArrayMemoExcep.Push("myItem2"); | |
| } | |
| } | |
| class CustomArray | |
| { | |
| private object[] _array; | |
| private int _size; | |
| private int _lastPositionAvailable; | |
| public CustomArray(int size) | |
| { | |
| if (size < 1) throw new ArgumentOutOfRangeException(); | |
| _size = size; | |
| _lastPositionAvailable = 0; | |
| _array = new object[size]; | |
| } | |
| public object Get(int index) | |
| { | |
| return _array[index]; | |
| } | |
| public void Push(object item) | |
| { | |
| if (_lastPositionAvailable >= _size) throw new OutOfMemoryException(); | |
| _array[_lastPositionAvailable] = item; | |
| _lastPositionAvailable++; | |
| } | |
| public void Pop() | |
| { | |
| _array[_lastPositionAvailable - 1] = null; | |
| _lastPositionAvailable--; | |
| } | |
| public void Remove(int index) | |
| { | |
| _array[index] = null; | |
| ShiftItems(index); | |
| _lastPositionAvailable--; | |
| } | |
| private void ShiftItems(int index) | |
| { | |
| for(int i = index; i < _lastPositionAvailable; i++) | |
| { | |
| _array[i] = _array[i + 1]; | |
| } | |
| } | |
| public void PrintArray() | |
| { | |
| string items = ""; | |
| for(int i = 0; i < _lastPositionAvailable; i++) | |
| { | |
| items = $"{items}{_array[i]},"; | |
| } | |
| Console.WriteLine($"Length: {_lastPositionAvailable}, Data: [{items}]"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment