From 54220c6fc7c6da227800d8952635cc29c9de7ffc Mon Sep 17 00:00:00 2001 From: "A.Novopoltsev" Date: Fri, 16 Dec 2022 23:20:57 +0300 Subject: [PATCH] =?UTF-8?q?=D0=AD=D1=82=D0=B0=D0=BF=201.=20=D0=A1=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=BC=D0=B0=D1=81=D1=81=D0=B8=D0=B2=D0=B0?= =?UTF-8?q?=20=D0=BD=D0=B0=20=D1=81=D0=BF=D0=B8=D1=81=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Warship/Warship/SetWarshipsGeneric.cs | 82 ++++++++++++++------------- 1 file changed, 43 insertions(+), 39 deletions(-) diff --git a/Warship/Warship/SetWarshipsGeneric.cs b/Warship/Warship/SetWarshipsGeneric.cs index e119426..141ba87 100644 --- a/Warship/Warship/SetWarshipsGeneric.cs +++ b/Warship/Warship/SetWarshipsGeneric.cs @@ -9,69 +9,73 @@ namespace Warship internal class SetWarshipsGeneric where T : class { - private readonly T[] _places; + private readonly List _places; - public int Count => _places.Length; + public int Count => _places.Count; + + private readonly int _maxCount; public SetWarshipsGeneric(int count) { - _places = new T[count]; + _maxCount = count; + _places = new List(); } public int Insert(T warship) { - return Insert(warship, 0); + if (_places.Count + 1 >= _maxCount) + return -1; + _places.Insert(0, warship); + return 0; } public int Insert(T warship, int position) { - int EmptyEl = -1; - - if (position >= Count || position < 0) + if (position >= _maxCount || position < 0) return -1; - - if (_places[position] == null) - { - _places[position] = warship; - return 1; - } - - else if (_places[position] != null) - { - for (int i = position + 1; i < Count; i++) - if (_places[i] == null) - { - EmptyEl = i; - break; - } - - if (EmptyEl == -1) - return -1; - - for (int i = EmptyEl; i > position; i--) - _places[i] = _places[i - 1]; - } - - _places[position] = warship; - return 1; + if (_places.Count + 1 >= _maxCount) + return -1; + _places.Insert(position, warship); + return position; } public T Remove(int position) { - if (position >= Count || position < 0 || _places[position] == null) + if (position >= _maxCount || position < 0) return null; T deleted = _places[position]; - _places[position] = null; + _places.RemoveAt(position); return deleted; } - public T Get(int position) + public T this[int position] { - if (position >= Count || position < 0) - return null; - - return _places[position]; + get + { + if (position < 0 || position >= _maxCount) + return null; + return _places[position]; + } + set + { + if (position < 0 || position >= _maxCount) + Insert(value, position); + } + } + public IEnumerable GetWarships() + { + foreach (var warship in _places) + { + if (warship != null) + { + yield return warship; + } + else + { + yield break; + } + } } } }