JS Goodness : Arrays And Strings - Given an unsorted array with integers, test if consecutive integers sum up to a number

1) Given an unsorted array with integers, return true or false if a consecutive integers sum up to a number.

// Example:
var array = [4, 2, 1, 300]
isConsectiveSum( array, 301 ) //true

Below is one possible way to approach,
Remember : so consecutive integers means, say 302 - then it is still a sum of 1+1+300, so it can be a sequence of numbers
Solution
http://jsbin.com/tusumup/1/edit?js,output

http://jsbin.com/fajujex/1/edit?html,js,output
 // 1) Given an unsorted array with integers, return true or false if a consecutive integers sum up to a number.  
 console.clear();  
 function isConsectiveSum(array, total){  
  console.log("function called for Consecutive array");  
  var sum =0;  
  var visitedNum =[]  
  var result = array.some(function(elem,index,array){  
    sum += elem  
    var temp =0   
    if(sum == total)  
     return true  
    else if(sum>total){  
     sum = elem  
     for(var k=visitedNum.length;k>0;--k){  
      sum += visitedNum[k-1]  
      if(sum === total)  
       return true  
     }         
    }  
    visitedNum.push(elem)  
  });  
  return result;  
 };  
 var array = [4, 2, 1,1, 300]  
 var result = isConsectiveSum(array,307)  
 console.log("My Result is" + result); //true  


Comments

Popular posts from this blog

Apache Airflow Wait Between Tasks

Groovy GoodNess – Converting a List to String

Java Spring Interview Questions