Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a missing number in a sequence using .reduce

Tags:

javascript

var o = [1,2,3,5,6,7,8]

var res = o.reduce(function(x,y){

   return !((y-x)===1)?y-1:'Nothing'

})
console.log(res)//7

Output should be 4, want to know if it is possible using reduce or functionally (Not through loops)? it only works if the missing value is before the last value of an array.

like image 324
Sean T Avatar asked Nov 01 '25 17:11

Sean T


1 Answers

You can use reduce to compute the actual sum of all elements and then subtract it from the target sum (n(a0+an)/2). This gives you the missing number.

var o = [1,2,3,5,6,7,8];

var len = o.length;
var sum = (len + 1) * (o[0] + o[len - 1]) / 2;
var res = sum  - o.reduce((x,y) => x + y);

console.log(res);

Note that this works with any starting value and any step, e.g. for [3,5,7,11] it will correctly print 9. The only requirement is that o should be an arithmetic progression.

like image 186
georg Avatar answered Nov 03 '25 08:11

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!