Accessing An Element Of An Array Through Negative Indexes
I want to access contents of an array by arbitrary indexes. Lets say we have an array with three elements in it. The modulo comes in handy here and solves the problem for any posit
Solution 1:
You can use
n
integern % l
integer in(-l, l)
n % l + l
integer in(0, 2*l)
(n % l + l) % l
integer in[0, l)
In JavaScript,
arr[(someInteger % arr.length + arr.length) % arr.length]
Alternatively, you can play with flooring, ceiling and truncating:
n - Math.floor(n / l) * l; // in [ 0,l)
n - Math.ceil (n / l) * l; // in (-l,0]
n - Math.trunc(n / l) * l; // in (-l,l)
Solution 2:
If the number is negative:
while(someInteger < 0)
someInteger += arr.length;
and then use array[ someInteger%arr.length ]
as you did earlier.
Post a Comment for "Accessing An Element Of An Array Through Negative Indexes"