Game matrix bounds checking
An AI for a game like connect 4 that uses a game matrix, would it be wise to check bounds using a nested if structure, or are there more efficient alternatives?
e.g:
Code:
if(x>1&&y>1) { //bounds check
if(matrix[y-2][x-2]==1) { //first index.
//...
}
}
or is it ok to index an array element that does not exist? (renderring the bounds check redundant) I think this will cause the program to crash:
Code:
matrix[y-2][x-2]; //when x=1 and y=1
Re: Game matrix bounds checking
Quote:
Originally posted by Panopticon
An AI for a game like connect 4 that uses a game matrix, would it be wise to check bounds using a nested if structure, or are there more efficient alternatives?
e.g:
Code:
if(x>1&&y>1) { //bounds check
if(matrix[y-2][x-2]==1) { //first index.
//...
}
}
Can't really say without seeing context. Depending on how you do other things in your code it may be beneficial to take other approaches. Post some more and I can tell you how I would personally handle the situation.
Quote:
Originally posted by Panopticon
or is it ok to index an array element that does not exist? (renderring the bounds check redundant) I think this will cause the program to crash:
Code:
matrix[y-2][x-2]; //when x=1 and y=1
Depends on what your definition of "okay" is. In logic it will be wrong, but your example is perfectly valid code which in most cases wouldn't even cause a runtime error. The only times that simply referencing (not writing to) an out-of-bounds index would cause a crash would be if the resultant memory location was 0 or some other invalid memory location.
If, however, you were to attempt to write to an invalid array index, you can't be certain of the result. If the array was on the stack, it could very well just write to another variable on the stack and not know it was doing so, or possibly to something on the heap, or it could crash your program. Obviously, none of which are good.
What it comes down to is just simply don't do it.