2015-07-01 74 views
0

我該如何去寫一個方法來創建一個人口爲n×n矩陣,像這樣:C#方法來創建一個N×N的矩陣

int[,] Matrix(int n) or int[][] Matrix(int n) for example for n = 5: 

1 2 3 4 5 
16 17 18 19 6 
15 24 25 20 7 
14 23 22 21 8 
13 12 11 10 9 
+2

那麼,你已經嘗試過了什麼? – cubrr

+1

你不明白什麼?使用新的?使用循環?使用'[]'? –

+0

他正在尋找一種算法來根據他的預期結果中指定的模式來填充矩陣。 –

回答

2

一種解決方案是這樣的:

static int[,] Matrix(int n) 
{ 
    if (n < 0) 
     throw new ArgumentException("n must be a positive integer.", "n"); 

    var result = new int[n, n];      

    int level = 0, 
     counter = 1; 
    while (level < (int)Math.Ceiling(n/2f)) 
    { 
     // Start at top left of this level. 
     int x = level, 
      y = level; 
     // Move from left to right. 
     for (; x < n - level; x++)   
      result[y, x] = counter++;    
     // Move from top to bottom. 
     for (y++, x--; y < n - level; y++)    
      result[y, x] = counter++;    
     // Move from right to left. 
     for (x--, y--; x >= level; x--)    
      result[y, x] = counter++;    
     // Move from bottom to top. Do not overwrite top left cell. 
     for (y--, x++; y >= level + 1; y--)    
      result[y, x] = counter++;    
     // Go to inner level. 
     level++; 
    } 

    return result; 
} 

以下是所得的矩陣(N 1和6之間)打印到控制檯:

Result

0

這可以在這個MSDN Example來實現。

Google Search Results

// Two-dimensional array. 
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; 
// The same array with dimensions specified. 
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; 
// A similar array with string elements. 
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, 
             { "five", "six" } }; 

// Three-dimensional array. 
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
           { { 7, 8, 9 }, { 10, 11, 12 } } }; 
// The same array with dimensions specified. 
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
             { { 7, 8, 9 }, { 10, 11, 12 } } }; 

// Accessing array elements. 
System.Console.WriteLine(array2D[0, 0]); 
System.Console.WriteLine(array2D[0, 1]); 
System.Console.WriteLine(array2D[1, 0]); 
System.Console.WriteLine(array2D[1, 1]); 
System.Console.WriteLine(array2D[3, 0]); 
System.Console.WriteLine(array2Db[1, 0]); 
System.Console.WriteLine(array3Da[1, 0, 1]); 
System.Console.WriteLine(array3D[1, 1, 2]); 

// Getting the total count of elements or the length of a given dimension. 
var allLength = array3D.Length; 
var total = 1; 
for (int i = 0; i < array3D.Rank; i++) { 
    total *= array3D.GetLength(i); 
} 
System.Console.WriteLine("{0} equals {1}", allLength, total); 

// Output: 
// 1 
// 2 
// 3 
// 4 
// 7 
// three 
// 8 
// 12 
// 12 equals 12