2011-03-31 161 views
7

我有2個數組。 我想將第一個數組的索引轉換爲第二個數組。 有沒有更好的辦法做到這一點比我下面有什麼?將一維數組索引轉換爲二維數組索引

Array array1[9]; 
Array array2[3][3]; 

// Index is the index of the 1D array 
public Point convert1Dto2D(int index) 
{ 
     Point p = new Point(); 

     switch (index) { 
      case 0: 
       p.x = 0; 
       p.y = 0; 
       break; 
      case 1: 
       p.x = 0; 
       p.y = 1; 
       break; 
      case 2: 
       p.x = 0; 
       p.y = 2; 
       break; 
      case 3: 
       p.x = 1; 
       p.y = 0; 
       break; 
      case 4: 
       p.x = 1; 
       p.y = 1; 
       break; 
      case 5: 
       p.x = 1; 
       p.y = 2; 
       break; 
      case 6: 
       p.x = 2; 
       p.y = 0; 
       break; 
      case 7: 
       p.x = 2; 
       p.y = 1; 
       break; 
      case 8: 
       p.x = 2; 
       p.y = 2; 
       break; 
     } 

return p; 
} 

回答

25
p.x = index/3; 
p.y = index % 3; 
+5

用於在y之前放置x。 – 2011-03-31 03:21:59

+0

@PeterOlson它爲什麼重要? – vexe 2014-08-31 09:45:46

+0

@vexe自從發表評論至今已有3年,所以我不記得我腦子裏想的是什麼。我想這與傳統而不是正確有關。 – 2014-08-31 15:36:27

5

如果你的第二個數組是3x3數組,你可以用數學模型和整數除法來做到這一點。

p.y = index % 3; 
p.x = index/3; 
+0

衛生署,由5秒擊敗。 ;) – Sapph 2011-03-31 03:19:09

2

我假設你運行的代碼在一個循環?如果是這樣

IEnumerable<Point> DoStuff(int length, int step) { 
    for (int i = 0; i < length; i++) 
     yield return new Point(i/step, i%step); 
} 

叫它

foreach (var element in DoStuff(9, 3)) 
    { 
     Console.WriteLine(element.X); 
     Console.WriteLine(element.Y); 
    }