Best Way to Check If Object Is Out of Bounds in Array

Best way to check if object is out of bounds in array

You could also make an extension to Array, so you will be able to check with if-let:

extension Array {
func at(index: Int) -> Element? {
if index < 0 || index > self.count - 1 {
return nil
}
return self[index]
}
}

let arr = [1, 2, 3]

if let value = arr.at(index: 2) {
print(value)
}

Checking for out of bounds in a 2D array

If you're trying to get all the neighbor cells and do something with them, for example add them, then you need to do some sort of bounds checking, for example something modified from this could work:

for (int i = 0; i < numOfRows; i++) {
for (int j = 0; j < numOfCols; j++) {
// check all bounds out of range:
int iMin = Math.max(0, i - 1);
int iMax = Math.min(numOfRows - 1, i + 1);
int jMin = Math.max(0, j - 1);
int jMax = Math.min(numOfCols - 1, j + 1);

// loop through the above numbers safely
for (int innerI = iMin; innerI <= iMax; innerI++) {
for (int innerJ = jMin; innerJ <= jMax; innerJ++) {
if (i != innerI && j != innerJ) {
// do what needs to be done
}
}
}
}
}

Caveat: code has not been compiled nor tested and is mainly to show you the idea of what can be done rather than a copy-paste solution

JavaScript Checking Array Out of Bounds

My suggestion is just to protect arena[player.pos.y + i + 1][player.pos.x + j] call by length comparisons:

for (i = 0; i < player.matrix.length; i++)
{
for (j = 0; j < player.matrix[i].length; j++)
{ // here we have an additional protection of arena dimensions
if(player.pos.y + i + 1 < arena.length && player.pos.x + j < arena[player.pos.y + i + 1].length)
{
if ((player.matrix[i][j] && arena[player.pos.y + i + 1][player.pos.x + j]) != 0)
result = true;
}
}
}

Also you may implement an additional method on arena object:

arena.isValid = function(a, b) {
// check for dimensions
if(a >= arena.length || b >= arena[a].length) {
return false;
}
// check if the value is undefined/null/0/false/""
if(!arena[a][b]) {
return false;
}
return true;
};

And so

for (i = 0; i < player.matrix.length; i++)
for (j = 0; j < player.matrix[i].length; j++)
if(player.matrix[i][j] && arena.isValid(player.pos.y + i + 1, player.pos.x + j))
result = true;

Checking out of bounds in Java

Absolutely do not use try-catch for this. Simply use:

boolean inBounds = (index >= 0) && (index < array.length);

Implementing the approach with try-catch would entail catching an ArrayIndexOutOfBoundsException, which is an unchecked exception (i.e. a subclass of RuntimeException). Such exceptions should never (or, at least, very rarely) be caught and dealt with. Instead, they should be prevented in the first place.

In other words, unchecked exceptions are exceptions that your program is not expected to recover from. Now, there can be exceptions (no pun intended) to this here and there. For instance, it has become common practice to check if a string is parable as an integer by calling Integer.parseInt() on it and catching the potential NumberFormatException (which is unchecked). This is considered OK, but always think twice before doing something like that.

Array Out of Bounds: Comparison with undefined, or length check?

The only correct way is to check the index vs. the length.

An element may be assigned the value undefined. It is just silly to use it for a sentinel here. (There may be other, valid and possibly overlapping, reasons for checking for undefined, but not "for an out of bound check" -- the code in the other question will present arguably wrong results when the value of the given arg is really undefined.)

Happy coding.

How Do I Check To See If I'm Out Of Bounds In An If Statement?

Instead of this

if (scores[a + 1] != null)

You check the Count(list) or Length(array):

if (a + 1 <= scores.Count)

It's not clar what you're trying to do here, but i guess there are much easier ways

//Largest to smallest

For example with LINQ:

var orderedCombos = Combos.Zip(scores, (c, s) => new{ Combo = c, Score = s})
.OrderByDescending(x => x.Score)
.Select(x => x.Combo)
.ToList();

(but you should really store both informations in the same class or at least don't link via index)

Get value from array if not out of bounds

Why not use the built-in ElementAtOrDefault method from Linq?

string[] names =
{ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };

int index = 20;

string name = names.ElementAtOrDefault(index);


Related Topics



Leave a reply



Submit