javascript - Finding the middle index between any two indexes in a circular array -
i have array , 3 indexes:
var arr = ['a', 'b', 'c', 'd']; var f = 0; // first element var l = arr.length - 1; // last element var c = 0; // current element
i'm trying write function makes index c
cycle through array. requirement never reach index l
. so, whenever c
reaches value, f
, l
need increased well.
a reasonable value work limit c thought middle point between f , l. function wrote this:
var mod = function(x, m) { var r = x%m; return r<0 ? r+m : r; } while (true) { console.log('f', f, 'l', l, 'c', c); if (c == l) { console.log('error'); } c = mod(c + 1, arr.length); if (c > mod(l - f, arr.length) / 2) { f = mod(f + 1, arr.length); l = mod(l + 1, arr.length); } }
it doesn't work, clearly. there nice simple formula modulo operator want or approach totally wrong?
here's fiddle try it: https://jsfiddle.net/wku37h9e/2/
edit: explaining purpose of bit long. let's in array stored positions of external elements have move around. when c
close l
, advance indexes. graphically this:
1. [f|c] [ ] [ ] [ l ] 2. [ f ] [ c ] [ ] [ l ] 3. [ l ] [ f ] [ c ] [ ] // here start moving things around 4. [ ] [ l ] [ f ] [ c ] 5. [ c ] [ ] [ l ] [ f ] 6. [ f ] [ c ] [ ] [ l ]
and on. more elements in array there more distance between indexes.
i use different normal version of mod take in account negative numbers.
i hope it's bit clearer now
a reasonable value work limit
c
thought middle point betweenf
,l
finding mean average between 2 values, low
, high
, in mod len
function midpoint(low, high, len) { var mid; low %= len; high %= len; while (low < 0) low += len; // these 2 lines while (high < low) high += len; // important direction mid = (low + high) / 2; // mean average mid %= len; // convert our mod return mid; }
so have
// works expected beyond range of mod midpoint( 1, -1, 9); // middle of 1..8 (mod 9) = 4.5 midpoint(-7, 5, 9); // middle of 2..5 (mod 9) = 3.5 midpoint(-6, 12, 9); // middle of 3..3 (mod 9) = 3 // , midpoint( 2, 5, 9); // middle of 2..5 (mod 9) = 3.5 midpoint( 5, 2, 9); // middle of 5..2 (mod 9) = 8 (we went other way around)
you don't have force mod until after whole calculation, if wanted following, lose direction around loop
function midpoint(a, b, len) { var mid; mid = (a + b) / 2; // mean average mid %= len; // convert our mod while (mid < 0) mid += len; // positive return mid; }
notice here, however
midpoint(-6, 3, 9); // middle of 3..3 (mod 9) = 7.5 midpoint( 3, 3 + 0 * 9, 9); // middle of 3..3 (mod 9) = 3 midpoint( 3, 3 + 1 * 9, 9); // middle of 3..3 (mod 9) = 7.5 midpoint( 3, 3 + 2 * 9, 9); // middle of 3..3 (mod 9) = 3
i.e. mid point of 3..3
(mod 9) both 3
, 7.5
, true, way around we've gone depends on k
(where b - = k * len + a
)
Comments
Post a Comment