2010-05-31 60 views
0

說我有一個參差不齊的數組,並且位置2,3被int 3所佔據。其他每個點都被int 0填充。我將如何填充2,3之後的所有位置,並使用4?我如何更改Jagged數組中某個點後面的所有內容?

0 0 0 0 0 0 

0 0 0 0 

0 0 0 3 0 0 

0 0 0 0 0 

這樣:

4 4 4 4 4 4 

4 4 4 4 

4 4 4 3 0 0 

0 0 0 0 0 

伊夫嘗試這種變化:

int a = 2; 
int b = 3; 

for (int x = 0; x < a; x++) 
{ 
    for (int y = 0; y < board.space[b].Length; y++) 
    { 
      board.space[x][y] = 4; 
    } 
} 

回答

0

試試這個。

private static void ReplaceElements(int[][] array, int x, int y, int newValue) 
{ 
    for (int i = 0; i <= x && i < array.Length; i++) 
    { 
     for (int j = 0; j < array[i].Length; j++) 
     { 
      if (j < y || i < x) 
       array[i][j] = newValue; 
     } 
    } 
} 

演示:

int[][] array = new int[4][]; 
array[0] = new int[] { 0, 0, 0, 0, 0, 0 }; 
array[1] = new int[] { 0, 0, 0, 0}; 
array[2] = new int[] { 0, 0, 0, 3, 0, 0}; 
array[3] = new int[] { 0, 0, 0, 0, 0 }; 

int x = 2; 
int y = 3; 
int newValue = 4; 

ReplaceElements(array, x, y, newValue); 

foreach (int[] inner in array) 
{ 
    Console.WriteLine(string.Join(" ", inner)); 
} 
0

最簡單的方法是把它檢查當前元素它是等於3。如果是,停止通過改變一些控制變量,否則變化值爲4.

bool done = false; 
for (int y = 0; y < board.Size && !done; ++y) 
{ 
    for (int x = 0; x < board.space[y].Length && !done; ++y) 
    { 
     if (board.space[y][x] == 3) done = true; 
     else board.space[y][x] = 4; 
    } 
} 
相關問題