c# - 如何在 C# 中获取多维数组的最小数量?
问题描述
这是到目前为止的代码:
public static class Vectors
{
public static int[] FindShortest(int[][] vectors)
{
throw new NotImplementedException("Waiting to be implemented.");
}
public static void Main(string[] args)
{
int[][] vectors =
{
new int[] { 1, 1, 1 },
new int[] { 2, 2, 2 },
new int[] { 3, 3, 3 }
};
int[] shortest = Vectors.FindShortest(vectors);
// Expected output: x: 1, y: 1, z: 1
Console.WriteLine(String.Format("x: {0}, y: {1}, z: {2}", shortest[0], shortest[1], shortest[2]));
}
}
该代码采用一组 3D 向量并返回最短的向量。
解决方案
private static double VectorLength(int[] v)
{
return Math.Sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
}
那么它只是一个最小值函数:
public static int[] FindShortest(int[][] vectors)
{
var minLength = double.MaxValue;
int[] minVec = Array.Empty<int>();
foreach(var v in vectors)
{
var vectorLength = VectorLength(v);
if (vectorLength < minLength) {
minLength = vectorLength;
minVec = v;
}
}
return minVec;
}
请记住,您确实会检查向量的长度是否为 3 等。
另外,如果您对浮点精度感到满意,您可以只使用 Vector3
推荐阅读
- mongodb - 如何在嵌入(discord.js)中映射来自猫鼬数据库的数据
- logic - 理解符号逻辑(来自 BCS 学习资源书)
- android - 从android中的其他类中删除动作模式
- json - yaml:使用 go 时解组错误
- javascript - 部分未显示在移动视图上
- react-native - 如何在反应原生图像组件中显示base64和uri
- python - SQLAlchemy - 最新的多对多关系
- reactjs - 从 API 获取所有数据后如何隐藏加载更多按钮?
- linux - linux命令输出一个csv文件(里面有不同的格式)
- python - 在不修改 C++ 代码的情况下从 Python 调用 C++