forked from llipio/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
JS solution and tests for Issue llipio#18 - Find missing number in ar…
…ray of consecutively increasing numbers
- Loading branch information
1 parent
f7980c5
commit a754996
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// 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} missingNum - the number missing from the input array | ||
*/ | ||
const solution = 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; | ||
}; | ||
|
||
module.exports = { | ||
solution | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
const expect = require('chai').expect; | ||
let solution = require('../solutions/18').solution; | ||
//solution = require('../yourSolution').solution; | ||
|
||
describe('Find missing number in array', () => { | ||
it('should return 7 for [5,6,8,9]', () => { | ||
const result = solution([5,6,8,9]); | ||
expect(result).to.equal(7); | ||
}); | ||
|
||
it('should return 94 for [89,90,91,92,93]', () => { | ||
const result = solution([89,90,91,92,93,95]); | ||
expect(result).to.equal(94); | ||
}); | ||
|
||
it('should return null if there is no missing number', () => { | ||
const result = solution([1,2,3,4,5]); | ||
expect(result).to.equal(null); | ||
}); | ||
}); |