2010-05-31 41 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; 
    } 
} 
相关问题