首页 > 解决方案 > 如何在 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 向量并返回最短的向量。

标签: c#

解决方案


您应该从实现向量长度方法开始: 向量长度

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


推荐阅读