2016-12-21 4 views
0

ユーザーが100の数字のリストを入力する必要のあるプログラムを作りたいと思っています。 結果は34行3列の2次元マトリックスでなければなりません(最後の行はコース数が1つだけです)。 これで、まず配列を昇順でソートします。次に、降順で各行を別々にソートする必要があります。2D配列の各行を個別にソートするにはどうすればよいですか?

これらはユーザーが入力数である場合、私は10個の要素

を含む二次元アレイで説明します:2、4、6、9、5、2、3、4、9、7 I配列を次のようにします:

3 2 2 
    5 4 4 
    9 7 6 
    9 

答えて

0

実際にする必要がある場合は、後で2D配列にコピーできる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); 
} 
0

あなたは別々のステップとして、ソートやリストラをすればそれは簡単です:

  1. はフラット(すなわち1次元)の配列で結果を収集します。

  2. フラットアレイを並べ替えます(Array.Sort(...)など)。

  3. フラットアレイをループして新しいデータ構造を構築します。ここでさらにソートする必要はありません。たびに[arr[n+2], arr[n+1], arr[n]]を新しい2D配列の行として取り、n = n + 3にジャンプしてください。

0

また、ソートされた入力構造をループして出力構造を作成することをお勧めします。あなたが望むものを達成するためには、任意のサイズの整数配列と2次元出力配列の必要な列数を取り、定義した結果を返します。

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; 
} 
関連する問題