我如何分别对2D数组的每一行分类



我想制作一个程序,用户必须输入100个数字列表。结果必须是一个具有34行和3列的2维矩阵(最后一行只有1个数字)。现在我要:首先通过上升顺序排序数组。然后,我想通过降序分开对每行分类。

我将用包含10个元素的二维数组演示

如果这些是用户输入的数字:2、4、6、9、5、2、3、4、9、7我希望阵列看起来像这样:

    3 2 2
    5 4 4
    9 7 6
    9

我认为,从1D数组开始更容易

Array.Sort(input); //input is an int[100]
//Now, sort each row in descending order
var comparer = Comparer<int>.Create((a, b) => b.CompareTo(a));
for (int row = 0; row < 99; r+=3) {
    Array.Sort(input, row, 3, comparer);
}

如果您作为单独的步骤进行排序和重组,则很简单:

  1. 收集结果以平面(即一维)数组。

  2. 对平面阵列进行排序(例如用Array.Sort(...))。

  3. 通过循环穿过平面阵列来建立新的数据结构。您无需在此处进行任何进一步的分类。每次将[arr[n+2], arr[n+1], arr[n]]作为新的2D数组中的行,然后跳到n = n + 3

我也赞成通过在分类的输入结构上循环创建输出结构。以下将实现您想要的。它将采用任何大小的整数数组和二维输出阵列所需的列数,并在定义时返回结果。

public static int?[,] SortInput(int[] input, int requiredColumnCount)
{
    // Guard conditions.
    if (input == null)
        throw new ArgumentNullException(nameof(input));
    if (input.Length < 1)
        throw new ArgumentOutOfRangeException(nameof(input));
    if (requiredColumnCount < 1)
        throw new ArgumentOutOfRangeException(nameof(requiredColumnCount));
    var inputLength = input.Length;
    // Sort the input array in ascending order.
    Array.Sort(input);
    // Dimension the output array.
    var requiredRowCount = (int)Math.Ceiling((decimal)inputLength / requiredColumnCount);
    var output = new int?[requiredRowCount, requiredColumnCount];
    // Setup variables to check for special handling of last output row.
    var lastRowIndex = output.GetUpperBound(0);
    var columnCountForLastRow = inputLength % requiredColumnCount;
    // Populate the output array.
    for (var inputIndex = 0; inputIndex < inputLength; inputIndex += requiredColumnCount)
    {
        var rowIndex = inputIndex / requiredColumnCount;
        // Special handling may be required if there are insufficient
        // input values to fully populate the last output row.
        if ((rowIndex == lastRowIndex) && (columnCountForLastRow != 0))
            requiredColumnCount = columnCountForLastRow;
        for (var columnIndex = 0; columnIndex < requiredColumnCount; columnIndex++)
        {
            output[rowIndex, columnIndex] = input[inputIndex + requiredColumnCount - columnIndex - 1];
        }
    }
    return output;
}

最新更新