The solution is to guard against unbounded inputs when writing to arrays.
You can use if statements to check if the value is within bounds, and throw an error otherwise.
if
Alternatively, a very simple solution is to use the % modulo operator to constrain the index like this:
%
array[input % array.length] = value; // will never go out of bounds
With the method above, any out-of-bounds input will be "wrapped around" in the range of 0:N.
For example, if the length of the array is 20 and you supply 10: 10 % 20 = 10, so nothing really changes when the supplied input is within bounds.
10 % 20 = 10
But if you supply an out-of-bounds index, say 25: 25 % 20 = 5, and it remains within bounds.
25 % 20 = 5
It's worthy to note that this approach also guards against negative inputs, because -25 % 20 equals 15.
-25 % 20
Edit: Fixed my numbers. Still waiting on my coffee, sorry.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The solution is to guard against unbounded inputs when writing to arrays.
You can use
if
statements to check if the value is within bounds, and throw an error otherwise.Alternatively, a very simple solution is to use the
%
modulo operator to constrain the index like this:With the method above, any out-of-bounds input will be "wrapped around" in the range of 0:N.
For example, if the length of the array is 20 and you supply 10:
10 % 20 = 10
, so nothing really changes when the supplied input is within bounds.But if you supply an out-of-bounds index, say 25:
25 % 20 = 5
, and it remains within bounds.It's worthy to note that this approach also guards against negative inputs, because
-25 % 20
equals 15.Edit: Fixed my numbers. Still waiting on my coffee, sorry.