Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7e61724

Browse files
Missing Number
1 parent c81562d commit 7e61724

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎11_Missing-Number/index.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /