-
Notifications
You must be signed in to change notification settings - Fork 1
/
ArrayHelpers.cs
77 lines (62 loc) · 1.88 KB
/
ArrayHelpers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
namespace Oeis.A002845
{
/// <summary>
/// Contains utility methods for array manipulation.
/// </summary>
internal static class ArrayHelpers
{
public static T[] RemoveElement<T>(T[] array, T item, out bool removed) where T : IComparable<T>
{
if (array == null || array.Length == 0)
{
removed = false;
return null;
}
var index = Array.BinarySearch(array, item);
if (index < 0)
{
removed = false;
return array;
}
removed = true;
if (array.Length == 1)
{
return null;
}
var newArray = new T[array.Length - 1];
if (index > 0)
{
Array.Copy(array, 0, newArray, 0, index);
}
if (index < array.Length - 1)
{
Array.Copy(array, index + 1, newArray, index, array.Length - 1 - index);
}
return newArray;
}
public static T[] InsertElement<T>(T[] array, T item) where T : IComparable<T>
{
if (array == null || array.Length == 0)
{
return new[] {item};
}
var index = ~Array.BinarySearch(array, item);
if (index < 0)
{
throw new InvalidOperationException("The item already exists.");
}
var newArray = new T[array.Length + 1];
if (index > 0)
{
Array.Copy(array, 0, newArray, 0, index);
}
newArray[index] = item;
if (index < newArray.Length - 1)
{
Array.Copy(array, index, newArray, index + 1, array.Length - index);
}
return newArray;
}
}
}