Skip to content

Commit

Permalink
Merge pull request #54 from zachnagatani/missing-num
Browse files Browse the repository at this point in the history
JS solution and tests for Issue #18 - Find missing number in array of…
  • Loading branch information
songz authored May 31, 2017
2 parents 6f829ff + dbd6af9 commit cc60d0d
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
46 changes: 46 additions & 0 deletions solutions/18.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Find missing number in array
// Return the missing number in an input array of consecutively increasing numbers.
// input: [5,6,8,9]
// output: 7

// Zach Nagatani

/**
* Finds and returns the missing number from an array of consecutively increasing numbers
* @param {Number[]} arr - An array of consecutively increasing numbers
* @returns {Number|null} missingNum - the number missing from the input array or null if none is found
*/
const solution1 = arr => {
let missingNum = null,
i = 0;

while (!missingNum && i < arr.length - 1) {
const current = arr[i],
next = arr[i + 1];

missingNum = next === current + 1 ? missingNum : next - 1;
i++;
}

return missingNum;
};

/**
* Finds and returns the missing number from an array of consecutively increasing numbers
* @param {Number[]} arr - An array of consecutively increasing numbers
* @returns {Number|null} missingNum - the number missing from the input array or null if none is found
*/
const solution2 = arr => {
let i = 1;

while (i < arr.length && arr[i - 1] + 1 === arr[i]) {
i++;
}

return i === arr.length ? null : arr[i - 1] + 1;
};

module.exports = {
solution1,
solution2
};
34 changes: 34 additions & 0 deletions test/18.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const expect = require('chai').expect;
let solution1 = require('../solutions/18').solution1,
solution2 = require('../solutions/18').solution2;
//solution = require('../yourSolution').solution;

describe('Find missing number in array', () => {
it('should return 7 for [5,6,8,9]', () => {
const result1 = solution1([5,6,8,9]),
result2 = solution2([5,6,8,9]);
expect(result1).to.equal(7);
expect(result2).to.equal(7);
});

it('should return 94 for [89,90,91,92,93,95]', () => {
const result1 = solution1([89,90,91,92,93,95]),
result2 = solution2([89,90,91,92,93,95]);
expect(result1).to.equal(94);
expect(result2).to.equal(94);
});

it('should return null if there is no missing number', () => {
const result1 = solution1([1,2,3,4,5]),
result2 = solution1([1,2,3,4,5]);
expect(result1).to.equal(null);
expect(result2).to.equal(null);
});

it('should return -8 for [-10,-9,-7,-6,-5]', () => {
const result1 = solution1([-10,-9,-7,-6,-5]),
result2 = solution1([-10,-9,-7,-6,-5]);
expect(result1).to.equal(-8);
expect(result2).to.equal(-8);
});
});

0 comments on commit cc60d0d

Please sign in to comment.