日期:2014-05-20 浏览次数:20902 次
// returns the nearest center to the input vector, using the L2 norm
public static double[] NearestCenter(double[] vector, double[][] centers)
{
// written in LINQ to "prove it can be done". easier to see that it is functional, too
return centers.Aggregate(centers[0], (old, cur) => (vector.Select((v, i) => v - old[i])
.Select(diff => diff * diff)
.Sum() >
vector.Select((v, i) => v - cur[i])
.Select(diff => diff * diff)
.Sum()) ? cur : old);
}
T Aggregate<T>(this IEnumerable<T> collection, T first, Func<T, T, T> foo)
{
T old = first;
T r;
foreach (var cur in collection)
{
r = foo(old, cur);
old = cur;
}
return r;
}