Here is my option. It is curious that it actually fills it with a snake and this is especially clearly seen if there is not enough data in the input array to completely fill the square and, under debugging:
0 0 0 10
0 0 0 0
0 0 0 0
0 0 0 0
0 0 20 10
0 0 0 0
0 0 0 0
0 0 0 0
0 0 20 10
0 0 0 31
0 0 0 0
0 0 0 0
0 44 20 10
0 0 0 31
0 0 0 0
0 0 0 0
0 44 20 10
0 0 55 31
0 0 0 0
0 0 0 0
The code itself:
void Main() { const int max = 4; int[] numbers = { 10, 20, 31, 44, 55, 66, 77, 88, 90, 91, 92, 93, 94, 95, 96, 97 }; var result = this.Putty(max, numbers); PrettyPrint(result, max); } // Define other methods and classes here public int[,] Putty(int size, int[] numbers) { int[,] matrix = new int[size, size]; int x = 0; int y = size - 1; int turnAbove = 0; int turnBelow = 0; var iter = numbers.GetEnumerator(); while (iter.MoveNext()) { matrix[x, y] = (int)iter.Current; PrettyPrint(matrix, size); x++; y++; if (x >= size && y >= size) { turnBelow++; y = 0; x = turnBelow; } else if (y >= size) { turnAbove++; x = 0; y = size - 1 - turnAbove; } else if (x >= size) { turnBelow++; y = 0; x = turnBelow; } } return matrix; } public void PrettyPrint(int[,] matrix, int max) { Console.WriteLine(); for (int i = 0; i < max; i++) { for (int j = 0; j < max; j++) Console.Write(matrix[i, j] + " "); Console.WriteLine(); } }
If your input numbers are not in order - the very algorithm, O (n)
The basis of the algorithm is the transition from the current cell x, y diagonally through the simultaneous increment of x and y.
Next you need to write the conditions for determining that we jumped over the edge of the array.
I counted three variants of departure: over the diagonal, when we flew beyond the vertical border; under the diagonal, when flew over the horizontal border and on the diagonal (flew simultaneously over both borders).
Probably, you can try to optimize the algorithm (reduce the number of auxiliary variables or condition branches), leaving room for creativity.
I also did not take into account the option when we have an array completely filled, and the input IEnumerable is not over yet.