Using Math instead of a Hammer
It’s been said that a person with a hammer views every problem as a nail. This happens all the time in coding. We are given a problem, and the easiest way to solve it seems to run through loops of code. Sometimes, you have to reach out to other disciplines. I was looking at a problem being discussed in a code camp meet-up yesterday.
“In Javascript, given an array of x items, where each item is an integer and all items are sorted by value (least to greatest), find the sum of all missing integers plus the integer following each missing integer.”
There were many for-loops on the board, and I could see that looping through the array would eventually give me a solution; however, I then thought surely given a set of integers where the least and greatest value are known I should be able to find a mathematical function that would give me the total. Then, using the “reduce” function I could get the sum of all values in the array. Finally from these two values I could determine the answer.
Here is the solution that I created:
function get_missing_sum( arr ) { if( arr.length < 2 ) return( 0 ); let csum = arr.reduce( (t,n) => { return( t+n); }); let min = arr.shift(); let max = arr.pop(); let range = (max - min); let psum = ((range + 1)*(min + max)) / 2; let missing = range - ( arr.length + 1 ); let sums = ( ( psum-csum ) * 2 ) + missing; return( sums ); } let narray = [ 1,2,5,7 ]; get_missing_sum( narray );
One of the concerns I had from the description of the problem was that there was no limit to the size of the array. Also, I didn’t want to make too many assumptions about the data set (e.g. how many consecutive integers might be missing). This was a fun exercise because it pushed me outside of coding and into more procedural thoughts. Of course my actual first thought was, “If the array is already sorted, this work should have been done in an earlier step”.