javascript - Finding a non-consecutive number pair in an array -
given array minimum length of 3 , maximum length of 5, contains uniquely occurring integers 0 4 in ascending order, need pick out 2 non-consecutive numbers it. non-consecutive refers numeric value, not position in array.
to clarify, here examples of valid arrays:
[ 1, 2, 3 ]
[ 0, 1, 2, 4 ]
[ 0, 3, 4 ]
for arrays above, valid answers be, respectively:
[ 1, 3 ]
[ 0, 2 ]
,[ 0, 4 ]
or[ 1, 4 ]
[ 0, 3 ]
or[ 0, 4 ]
furthermore, in cases there more 1 valid answer, need selected @ random, if @ possible (for instance don't want favor sequences begin lowest number, occur if began checking left right , stopped checking found 1 valid solution).
what efficient way of tackling problem in javascript?
you use 2 nested iterations , build new array choosing random result.
function getnonconsecutives(array) { return array.reduce((r, a, i, aa) => r.concat(aa.slice(i + 2).map(b => [a, b])), []); } console.log(getnonconsecutives([ 0, 1, 2, 4 ]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
according bee157's answer, use random choice constraint, length first index , add needed space second index.
the problem is, due nature of choosing first number first, distribution of result not equal.
function getnonconsecutives(array) { var = math.floor(math.random() * (array.length - 2)); return [ array[i], array[math.floor(math.random() * (array.length - 2 - i)) + 2 + i] ]; } console.log(getnonconsecutives([ 0, 1, 2, 4 ]));
Comments
Post a Comment