2022-10-27 15:46:11 +04:00

110 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMachine
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetTankGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetTankGeneric(int count)
{
_places = new T[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый танк</param>
/// <returns></returns>
public int Insert(T tank)
{
if (tank == null)
{
return -1;
}
for (int i = Count -1; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = tank;
return 0;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="tank">Добавляемый танк</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T tank, int position)
{
if (position < 0 || position > Count)
{
return -1;
}
int firstNullElementIndex = position; //индекс первого нулевого элемента
while(_places[firstNullElementIndex] != null)
{
if (firstNullElementIndex >= Count)
{
return -1;
}
firstNullElementIndex++;
}
for (int i = firstNullElementIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = tank;
return 0;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
if (_places[position] == null)
{
return null;
}
var result = _places[position];
_places[position] = null;
return result;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Get(int position)
{
if (_places[position] != null)
{
return _places[position];
}
return null;
}
}
}