2
votes

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();
        }
        
    }
}
1
it is index out of bounds because the array starts at 0 and ends at 4, this = 5 indexs, 0, 1, 2, 3, 4, if you want to keep the same code then make it 6, and same goes for the 2d part - Getwrong
Sorry, i explained poorly, I edited it now. In my program I used < array.GetLength(0) / < array.GetLength(1) , so it wouldn't really matter, the problem is still there - Putzfrau
My bad, i didnt try the code out until just then. il lhave another look - Getwrong
is it not just because the for loops are the wrong way around? now that i actually look at it in visual studio - Getwrong
y should go to board.GetLength(0) instead of GetLength(1). And similarly, x uses the wrong bounds, too. - György Kőszeg

1 Answers

1
votes

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