Advent of Code 2022: Day 4
Comparing two numbers
by Amy L
HTML
<link rel="stylesheet" href="https://adventofcode.com/static/style.css?30">
<h1><a href="https://adventofcode.com/2022/day/4" target="_blank">Day 4</a></h1>
<diV class="puzzle-input">
<label for="INPUT_DATA">Input</label>
<textarea id="INPUT_DATA" autocomplete="off" placeholder="paste your input here" rows="7" cols="50"></textarea>
</diV>
<dl>
<dt>Part 1</dt>
<dd>
<label>Answer:
<input type="text" id="answer1" readonly />
</label>
</dd>
<dt>Part 2</dt>
<dd>
<label>Answer:
<input type="text" id="answer2" readonly />
</label>
</dd>
</dl>
JavaScript 1.7
function Day4(input) {
function solvePart1(pairs) {
const contains = pairs.filter((pair) =>
pairContainsTheOther(pair, sectionFullyContainsAnother)
);
return contains.length;
}
function solvePart2(pairs) {
const contains = pairs.filter((pair) =>
pairContainsTheOther(pair, sectionPartiallyContainsAnother)
);
return contains.length;
}
const pairs = getPairs(input);
const part1 = solvePart1(pairs);
const part2 = solvePart2(pairs);
return {part1, part2};
}
document.addEventListener('DOMContentLoaded', () => {
getInputData('INPUT_DATA', (input) => {
const answers = Day4(input);
const [answer1El, answer2El] = [
document.getElementById('answer1'),
document.getElementById('answer2')
];
answer1El.value = answers.part1;
answer2El.value = answers.part2;
});
});
/*******************************************************************
Utility libs
**/
function getPairs(input) {
return input
.split('\n')
.map((pair) => {
const [elf1, elf2] = pair.split(',');
const [start1, end1] = elf1.split('-');
const [start2, end2] = elf2.split('-');
return {
elf1: {
start: parseInt(start1),
end: parseInt(end1)
},
elf2: {
start: parseInt(start2),
end: parseInt(end2)
},
};
});
}
function pairContainsTheOther({elf1, elf2}, comparisonMethod) {
return comparisonMethod(elf1, elf2) || comparisonMethod(elf2, elf1);
}
function sectionFullyContainsAnother(section, otherSection) {
const startsBeforeOtherSection = section.start <= otherSection.start;
const endsAfterOtherSection = section.end >= otherSection.end;
return startsBeforeOtherSection && endsAfterOtherSection;
}
function sectionPartiallyContainsAnother(section, otherSection) {
const sectionEndTouchesOtherSectionStart = section.end >= otherSection.start;
const sectionEndEndsWithinOtherSectionEnd = section.end <= otherSection.end;
return...