Skip to content

Commit

Permalink
Merge pull request #418 from aalmada/VectorExtensions
Browse files Browse the repository at this point in the history
Extended Average and Median to support IEnumerable and Vector2
  • Loading branch information
NeerajW committed Dec 27, 2016
2 parents 11f0e24 + c9da1f4 commit e3c6d78
Showing 1 changed file with 92 additions and 9 deletions.
101 changes: 92 additions & 9 deletions Assets/HoloToolkit/Utilities/Scripts/Extensions/VectorExtensions.cs
Expand Up @@ -53,33 +53,116 @@ public static Vector3 InverseTransformPoint(this Vector3 point, Vector3 translat
return Vector3.Scale(scaleInv, (Quaternion.Inverse(rotation) * (point - translation)));
}

public static Vector3 Average(ICollection<Vector3> vectors)
public static Vector2 Average(this IEnumerable<Vector2> vectors)
{
if (vectors.Count == 0)
float x = 0f;
float y = 0f;
int count = 0;
foreach (var pos in vectors)
{
x += pos.x;
y += pos.y;
count++;
}
return new Vector2(x / count, y / count);
}

public static Vector3 Average(this IEnumerable<Vector3> vectors)
{
float x = 0f;
float y = 0f;
float z = 0f;
int count = 0;
foreach (var pos in vectors)
{
x += pos.x;
y += pos.y;
z += pos.z;
count++;
}
return new Vector3(x / count, y / count, z / count);
}

public static Vector2 Average(this ICollection<Vector2> vectors)
{
int count = vectors.Count;
if (count == 0)
{
return Vector2.zero;
}

float x = 0f;
float y = 0f;
foreach (var pos in vectors)
{
x += pos.x;
y += pos.y;
}
return new Vector2(x / count, y / count);
}

public static Vector3 Average(this ICollection<Vector3> vectors)
{
int count = vectors.Count;
if (count == 0)
{
return Vector3.zero;
}

var x = 0f;
var y = 0f;
var z = 0f;
float x = 0f;
float y = 0f;
float z = 0f;
foreach (var pos in vectors)
{
x += pos.x;
y += pos.y;
z += pos.z;
}
return new Vector3(x / vectors.Count, y / vectors.Count, z / vectors.Count);
return new Vector3(x / count, y / count, z / count);
}

public static Vector2 Median(this IEnumerable<Vector2> vectors)
{
int count = vectors.Count();
if (count == 0)
{
return Vector2.zero;
}

return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
}

public static Vector3 Median(this IEnumerable<Vector3> vectors)
{
int count = vectors.Count();
if (count == 0)
{
return Vector3.zero;
}

return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
}

public static Vector2 Median(this ICollection<Vector2> vectors)
{
int count = vectors.Count;
if (count == 0)
{
return Vector2.zero;
}

return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
}

public static Vector3 Median(ICollection<Vector3> vectors)
public static Vector3 Median(this ICollection<Vector3> vectors)
{
if (vectors.Count == 0)
int count = vectors.Count;
if (count == 0)
{
return Vector3.zero;
}

return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(vectors.Count / 2);
return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
}
}
}

0 comments on commit e3c6d78

Please sign in to comment.