18 Star 133 Fork 63

编程语言算法集 / C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Manhattan.cs 1.09 KB
一键复制 编辑 原始数据 按行查看 历史
Gerson Jr 提交于 2023-12-30 10:33 . Switch to file-scoped namespaces (#430)
using System;
using System.Linq;
namespace Algorithms.LinearAlgebra.Distances;
/// <summary>
/// Implementation fo Manhattan distance.
/// It is the sum of the lengths of the projections of the line segment between the points onto the coordinate axes.
/// In other words, it is the sum of absolute difference between the measures in all dimensions of two points.
///
/// Its commonly used in regression analysis.
/// </summary>
public static class Manhattan
{
/// <summary>
/// Calculate Manhattan distance for two N-Dimensional points.
/// </summary>
/// <param name="point1">First N-Dimensional point.</param>
/// <param name="point2">Second N-Dimensional point.</param>
/// <returns>Calculated Manhattan distance.</returns>
public static double Distance(double[] point1, double[] point2)
{
if (point1.Length != point2.Length)
{
throw new ArgumentException("Both points should have the same dimensionality");
}
// distance = |x1-y1| + |x2-y2| + ... + |xn-yn|
return point1.Zip(point2, (x1, x2) => Math.Abs(x1 - x2)).Sum();
}
}
C#
1
https://gitee.com/TheAlgorithms/C-Sharp.git
git@gitee.com:TheAlgorithms/C-Sharp.git
TheAlgorithms
C-Sharp
C-Sharp
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891