Added FlexArrayInt and created FlexArrayString.cs
This commit is contained in:
commit
d620ec163d
11 changed files with 5391 additions and 0 deletions
110
FlexArray/FlexArrayInt.cs
Normal file
110
FlexArray/FlexArrayInt.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
namespace FlexArray;
|
||||
|
||||
public sealed class FlexArrayInt
|
||||
{
|
||||
public const int DefaultStartSize = 4;
|
||||
private int[] _data;
|
||||
|
||||
public int Count { get; private set; }
|
||||
public int Capacity => _data.Length;
|
||||
|
||||
public int this[int index]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (index < 0 || index > Count)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
return _data[index];
|
||||
}
|
||||
}
|
||||
|
||||
public bool Remove(int value, bool firstOnly)
|
||||
{
|
||||
var removedAny = false;
|
||||
for (var i = 0; i < Count; i++)
|
||||
{
|
||||
if (value != _data[i])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
RemoveAt(i--);
|
||||
removedAny = true;
|
||||
if (firstOnly)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return removedAny;
|
||||
}
|
||||
|
||||
public bool RemoveAt(int index)
|
||||
{
|
||||
if (index < 0 || index >= Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (index != Count - 1)
|
||||
{
|
||||
ShiftLeft(index);
|
||||
|
||||
}
|
||||
|
||||
Count--;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ShiftLeft(int fromIndex)
|
||||
{
|
||||
for (var i = fromIndex; i < Count; i++)
|
||||
{
|
||||
_data[i] = _data[i + 1];
|
||||
}
|
||||
}
|
||||
public FlexArrayInt(int? initialSize = null)
|
||||
{
|
||||
var size = Math.Max(0, initialSize ?? DefaultStartSize);
|
||||
_data = new int[size];
|
||||
}
|
||||
|
||||
public void Add(int value)
|
||||
{
|
||||
if (Capacity == Count)
|
||||
{
|
||||
Grow();
|
||||
}
|
||||
|
||||
_data[Count++] = value;
|
||||
}
|
||||
|
||||
public bool Contains(int value)
|
||||
{
|
||||
if (Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < Count; i++)
|
||||
{
|
||||
if (_data[i] == value)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
private void Grow()
|
||||
{
|
||||
var newData = new int[Capacity * 2];
|
||||
Array.Copy(_data, newData, Count);
|
||||
_data = newData;
|
||||
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue