How to Find the Missing Term in an Arithmetic Progression in Javascript

1 min read 229 words

The challenge

An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers that have been given to you. The rest of the given series is the same as the original AP. Find the missing term.

You have to write a function that receives a list, list size will always be at least 3 numbers. The missing term will never be the first or last one.

Example:

findMissing([1, 3, 5, 9, 11]) == 7

The solution in Javascript

Option 1:

var findMissing = function (l) {  
  return ((l[0]+l[l.length-1])*(l.length+1))/2-(l.reduce((a,b)=>a+b))
}

Option 2:

var findMissing = function (list) {
  let delta = (list[list.length - 1] - list[0])/list.length;
  return list.find( (el,ind) => el !== ind*delta + list[0]) - delta;
}

Option 3:

var findMissing = function (list) {  
  var listLen = list.length;
  var iter = (list[listLen-1]-list[0])/listLen;
  
  for(i = 0; i < listLen; i++){
    var next = list[i] + iter
    if(next != list[i+1]){
      return next;
    }
  }
}

Test cases to validate our solution

for (let i = 0;i < 10;++i) {
  fixture.random (1+i*5,0) ;
  fixture.random (1+i*5,10) ;
  fixture.random (1+i*5,100) ;
  fixture.random (1+i*5,1000) ;
  fixture.random (1+i*5,10000) ;
  fixture.random (1+i*5,100000) ;
}
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags