2010-05-31 4 views
0

Disons que j'ai un tableau dentelé, et la position 2,3 est prise par int 3. Chaque autre point est rempli avec int 0. Comment est-ce que je devrais remplir toutes les positions derrière 2,3 avec un 4?Comment puis-je tout changer derrière un certain point dans un tableau Jagged?

0 0 0 0 0 0 

0 0 0 0 

0 0 0 3 0 0 

0 0 0 0 0 

à ceci:

4 4 4 4 4 4 

4 4 4 4 

4 4 4 3 0 0 

0 0 0 0 0 

Ive a essayé des variations de cette:

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; 
    } 
} 

Répondre

0

essayer.

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; 
     } 
    } 
} 

Démo:

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

La serait plus simple d'avoir le vérifier si l'élément actuel, il est égal à 3. Le cas échéant, arrêter en modifiant certaines variables de contrôle, sinon le changement la valeur à 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; 
    } 
} 
Questions connexes