Reputation: 11
In the following C# code I want to create a 2D Array with the size of [5,2]. If I understand it correctly, that should look like this:
0 1 2
0[0,0] [0,1] [0,2]
1[1,0] [1,1] [1,2]
2[2,0] [2,1] [2,2]
3[3,0] [3,1] [3,2]
4[4,0] [4,1] [4,2]
But why does my program throw out an
IndexOutOfRangeException
...?
using System;
namespace program {
class program{
Random random = new Random();
int[,] board = new int[5,2];
public program(){
Print2DArray(randomBoard(0.5,board));
}
public int[,] randomBoard(double chance, int[,] board){
int[,] temp = board;
for(int y = 0; y < board.GetLength(1); y++){
for(int x = 0; x < board.GetLength(0); x++){
if(random.NextDouble() <= chance){
board[y,x] = 1;
} else {
board[y,x] = 0;
}
}
}
return temp;
}
public static void Print2DArray<T>(T[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i,j] + "\t");
}
Console.WriteLine();
}
}
static void Main(string[] args){
program program1 = new program();
}
}
}
Upvotes: 1
Views: 58
Reputation: 1025
In your code, y
goes from 0
to number of elements in dimension 1
while x
goes 0
to number of elements in dimension 0
However, inside your for
loop you seem to have the dimensions swapped,
board[y,x] = 1; // change this to board [x,y] = 1;
similarly for the else
condition it should be board[x,y] = 0
Upvotes: 1