Skip to content

Instantly share code, notes, and snippets.

@tjeastmond
Last active December 3, 2024 19:26
Show Gist options
  • Save tjeastmond/a3f9b37f23d24e27f4fc313d6cbec8c8 to your computer and use it in GitHub Desktop.
Save tjeastmond/a3f9b37f23d24e27f4fc313d6cbec8c8 to your computer and use it in GitHub Desktop.
Find the missing numbers in a range
export default function missingNumbers(numbers) {
const numSet = new Set(numbers);
let max = Math.max(...numbers);
let min = Math.min(...numbers);
return Array.from({ length: max - min }, (_, i) => i + min).filter(
(num) => num > 0 && !numSet.has(num),
);
}
import missingNumbers from "./missingNumbers.js";
function test_missing_numbers() {
function arraysEqual(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
// Test cases
const testCases = [
{ input: [9, 6, 10, 5], expected: [7, 8] },
{ input: [22, 23, 20, 15], expected: [16, 17, 18, 19, 21] },
{ input: [9, 6, 10, 5, -1], expected: [7, 8] },
{ input: [1, 2.5, 4.25, 2.75], expected: [3, 4] },
];
testCases.forEach(({ input, expected }, index) => {
const result = missingNumbers(input);
if (arraysEqual(result, expected)) {
console.log(`Test case ${index + 1} passed.`);
} else {
console.log(`Test case ${index + 1} failed. Expected ${expected}, but got ${result}.`);
}
});
}
test_missing_numbers();
{
"type": "module"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment