|
| 1 | +// Missing Number |
| 2 | +// Write a function that takes in an array of numbers (between 0 and 9) and finds what number is missing |
| 3 | + |
| 4 | +// assuming array is between 0 and 9 and only one num is missing |
| 5 | +const missingNumberBasic = numArr => { |
| 6 | + const totalPossible = 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 |
| 7 | + const arrTotal = numArr.reduce((acc, num) => { |
| 8 | + return acc + num |
| 9 | + }, 0) |
| 10 | + return totalPossible - arrTotal |
| 11 | +} |
| 12 | + |
| 13 | +console.log(missingNumberBasic([0, 3, 5, 8, 4, 6, 1, 9, 7])) |
| 14 | +console.log(missingNumberBasic([1, 2, 5, 0, 6, 7, 9, 3, 4])) |
| 15 | + |
| 16 | +// |
| 17 | +// |
| 18 | +// assuming a sequence of any positive numbers and one is missing (between the lowest and greatest numbers in the sequence) |
| 19 | +const missingNumberAny = numArr => { |
| 20 | + return ( |
| 21 | + numArr |
| 22 | + .sort((num1, num2) => { |
| 23 | + return num1 - num2 |
| 24 | + }) |
| 25 | + .find((num, i, array) => { |
| 26 | + // every number in the array minus its index should equal the first number, so return the first number that doesn't (it's the number after the missing number) |
| 27 | + return num - i !== array[0] |
| 28 | + }) - 1 |
| 29 | + ) |
| 30 | +} |
| 31 | + |
| 32 | +console.log(missingNumberAny([7, 5, 8, 4])) |
| 33 | +console.log(missingNumberAny([1, 2, 5, 0, 6, 7, 9, 3, 4])) |
| 34 | +console.log(missingNumberAny([345, 349, 347, 346])) |
0 commit comments