Skip to content

Commit

Permalink
Solve 20b
Browse files Browse the repository at this point in the history
  • Loading branch information
ttencate committed Dec 20, 2016
1 parent e70e782 commit da1de6c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 20_javascript/20b.js
@@ -0,0 +1,30 @@
#!/usr/bin/env node

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString();
const lines = input.split('\n').filter(line => line.indexOf('-') > 0);
const ranges = lines.map((line) => {
const parts = line.split('-');
return {
start: parseInt(parts[0], 10),
end: parseInt(parts[1], 10),
};
});
ranges.sort((a, b) => {
if (a.start < b.start) return -1;
if (a.start > b.start) return 1;
return 0;
});
const MAX_IP = 4294967295;
ranges.push({ start: MAX_IP + 1, end: MAX_IP + 1 });

let candidate = 0;
let count = 0;
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
if (range.start > candidate) {
count += range.start - candidate;
}
candidate = Math.max(candidate, range.end + 1);
}
console.log(count);
4 changes: 4 additions & 0 deletions 20_javascript/README.md
Expand Up @@ -6,3 +6,7 @@ well.
Part one is easy: just sort the ranges by start value, run through increasing
your candidate IP address to be beyond each of the ranges, and if you encounter
one that starts after the candidate, you're done.

Part two has a similar approach, just with a bit more careful bookkeeping. For
convenience, I pushed a sentinel range onto the end which is one past the final
possible IP address. JavaScript's 64-bit doubles let you do that.

0 comments on commit da1de6c

Please sign in to comment.