Этап 1. Смена массива на список

This commit is contained in:
A.Novopoltsev 2022-12-16 23:20:57 +03:00
parent e2969fef09
commit 54220c6fc7

View File

@ -9,69 +9,73 @@ namespace Warship
internal class SetWarshipsGeneric<T> internal class SetWarshipsGeneric<T>
where T : class where T : class
{ {
private readonly T[] _places; private readonly List<T> _places;
public int Count => _places.Length; public int Count => _places.Count;
private readonly int _maxCount;
public SetWarshipsGeneric(int count) public SetWarshipsGeneric(int count)
{ {
_places = new T[count]; _maxCount = count;
_places = new List<T>();
} }
public int Insert(T warship) 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) public int Insert(T warship, int position)
{ {
int EmptyEl = -1; if (position >= _maxCount || position < 0)
if (position >= Count || position < 0)
return -1; return -1;
if (_places.Count + 1 >= _maxCount)
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; return -1;
_places.Insert(position, warship);
for (int i = EmptyEl; i > position; i--) return position;
_places[i] = _places[i - 1];
}
_places[position] = warship;
return 1;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position >= Count || position < 0 || _places[position] == null) if (position >= _maxCount || position < 0)
return null; return null;
T deleted = _places[position]; T deleted = _places[position];
_places[position] = null; _places.RemoveAt(position);
return deleted; return deleted;
} }
public T Get(int position) public T this[int position]
{ {
if (position >= Count || position < 0) get
{
if (position < 0 || position >= _maxCount)
return null; return null;
return _places[position]; return _places[position];
} }
set
{
if (position < 0 || position >= _maxCount)
Insert(value, position);
}
}
public IEnumerable<T> GetWarships()
{
foreach (var warship in _places)
{
if (warship != null)
{
yield return warship;
}
else
{
yield break;
}
}
}
} }
} }