2010-01-28 181 views
0

我有一個int陣列到dimentions:如何刪除二維數組中的一行和一列?

int[,] intArray2D = new int[3,3]; 

我想有兩種方法,例如:

int[,] removeLine(int[,] array, int arrayColumnsCount, int lineToRemove){...} 
int[,] removeColumn(int[,] array, int arrayColumnsCount, int columnToRemove){...} 

所以,具有該陣列:

1 2 3 
4 5 6 
7 8 9 

調用使用lineToRemove = 1的removeLine方法我必須得到數組:

1 2 3 
7 8 9 

調用帶有columnToRemove = 1 columnLine方法我得數組:

1 3 
4 6 
7 9 

你有什麼建議的實施?

感謝

RT

回答

2

因爲數組不打算在其中添加&刪除項目的情況下,你應該使用更合適的數據結構。

LinkedList是最好的一個使用,當你期望會有很多的增加和刪除在中間或列表的開始。

列表工作正常,當你只是從最後添加和刪除。

你會通過導入使用:

using System.Collections.Generic; 

和編碼:

LinkedList<LinkedList<int>> grid = new LinkedList<LinkedList<int>>() 
grid.Add(new LinkedList<int>()); //repeat for each column/row 
+0

尼斯尖。我使用了泛型列表,算法很簡單。 謝謝:)。 – Ricardo 2010-01-29 11:19:40

+0

性能應該會更好...... – 2010-01-29 12:18:32

2

數組的大小不是動態的,所以你必須創建一個新的數組,填寫您要保留的值,並忽略要刪除的人。

2

非常基本的僞代碼:

removeLine(...) { 
    create array with 1 less line 
    loop through lines of original array 
     if line index == lineToRemove 
      continue loop 

removeColumns(...) { 
    create array with 1 less column 
    loop through columns of original array 
     if column index == columnToRemove 
      continue loop 
相關問題