forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VecN.cs
115 lines (99 loc) · 2.9 KB
/
VecN.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
namespace Algorithms.Search.AStar;
/// <summary>
/// Vector Struct with N Dimensions.
/// </summary>
public struct VecN : IEquatable<VecN>
{
private readonly double[] data;
/// <summary>
/// Initializes a new instance of the <see cref="VecN" /> struct.
/// </summary>
/// <param name="vals">Vector components as array.</param>
public VecN(params double[] vals) => data = vals;
/// <summary>
/// Gets the dimension count of this vector.
/// </summary>
public int N => data.Length;
/// <summary>
/// Returns the Length squared.
/// </summary>
/// <returns>The squared length of the vector.</returns>
public double SqrLength()
{
double ret = 0;
for (var i = 0; i < data.Length; i++)
{
ret += data[i] * data[i];
}
return ret;
}
/// <summary>
/// Returns the Length of the vector.
/// </summary>
/// <returns>Length of the Vector.</returns>
public double Length() => Math.Sqrt(SqrLength());
/// <summary>
/// Returns the Distance between this and other.
/// </summary>
/// <param name="other">Other vector.</param>
/// <returns>The distance between this and other.</returns>
public double Distance(VecN other)
{
var delta = Subtract(other);
return delta.Length();
}
/// <summary>
/// Returns the squared Distance between this and other.
/// </summary>
/// <param name="other">Other vector.</param>
/// <returns>The squared distance between this and other.</returns>
public double SqrDistance(VecN other)
{
var delta = Subtract(other);
return delta.SqrLength();
}
/// <summary>
/// Substracts other from this vector.
/// </summary>
/// <param name="other">Other vector.</param>
/// <returns>The new vector.</returns>
public VecN Subtract(VecN other)
{
var dd = new double[Math.Max(data.Length, other.data.Length)];
for (var i = 0; i < dd.Length; i++)
{
double val = 0;
if (data.Length > i)
{
val = data[i];
}
if (other.data.Length > i)
{
val -= other.data[i];
}
dd[i] = val;
}
return new VecN(dd);
}
/// <summary>
/// Is used to compare Vectors with each other.
/// </summary>
/// <param name="other">The vector to be compared.</param>
/// <returns>A value indicating if other has the same values as this.</returns>
public bool Equals(VecN other)
{
if (other.N != N)
{
return false;
}
for (var i = 0; i < other.data.Length; i++)
{
if (Math.Abs(data[i] - other.data[i]) > 0.000001)
{
return false;
}
}
return true;
}
}