Skip to content

Commit

Permalink
Add Day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
dominique-mueller committed Dec 2, 2024
1 parent 94acbef commit 5bec5e7
Show file tree
Hide file tree
Showing 5 changed files with 1,212 additions and 1 deletion.
74 changes: 74 additions & 0 deletions day-2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Day 2: Red-Nosed Reports

<br>

## Part 1

Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office.

While the [Red-Nosed Reindeer nuclear fusion/fission plant](https://adventofcode.com/2015/day/19) appears to contain no sign of the Chief
Historian, the engineers there run up to you as soon as they see you. Apparently, they **still** talk about the time Rudolph was saved
through molecular synthesis from a single electron.

They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed
reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently
searching every corner of the facility. You offer to help with the unusual data.

The unusual data (your puzzle input) consists of many **reports**, one report per line. Each report is a list of numbers called **levels**
that are separated by spaces. For example:

```txt
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
```

This example data contains six reports each containing five levels.

The engineers are trying to figure out which reports are **safe**. The Red-Nosed reactor safety systems can only tolerate levels that are
either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true:

- The levels are either **all increasing** or **all decreasing**.
- Any two adjacent levels differ by **at least one** and **at most three**.

In the example above, the reports can be found safe or unsafe by checking those rules:

- `7 6 4 2 1`: **Safe** because the levels are all decreasing by 1 or 2.
- `1 2 7 8 9`: **Unsafe** because `2 7` is an increase of 5.
- `9 7 6 2 1`: **Unsafe** because `6 2` is a decrease of 4.
- `1 3 2 4 5`: **Unsafe** because `1 3` is increasing but `3 2` is decreasing.
- `8 6 4 4 1`: **Unsafe** because `4 4` is neither an increase or a decrease.
- `1 3 6 7 9`: **Safe** because the levels are all increasing by 1, 2, or 3.

So, in this example, `2` reports are **safe**.

Analyze the unusual data from the engineers. **How many reports are safe?**

<br>

## Part 2

The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener.

The Problem Dampener is a reactor-mounted module that lets the reactor safety systems **tolerate a single bad level** in what would
otherwise be a safe report. It's like the bad level never happened!

Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts
as safe.

More of the above example's reports are now safe:

- `7 6 4 2 1`: **Safe** without removing any level.
- `1 2 7 8 9`: **Unsafe** regardless of which level is removed.
- `9 7 6 2 1`: **Unsafe** regardless of which level is removed.
- `1 3 2 4 5`: **Safe** by removing the second level, `3`.
- `8 6 4 4 1`: **Safe** by removing the third level, `4`.
- `1 3 6 7 9`: **Safe** without removing any level.

Thanks to the Problem Dampener, `4` reports are actually **safe**!

Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. **How many reports are
now safe?**
25 changes: 25 additions & 0 deletions day-2/day-2.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, it } from 'node:test';
import assert from 'node:assert';
import path from 'node:path';

import { determineNumberOfSafeReports, determineNumberOfSafeReportsWithProblemDampener } from './day-2';

describe('Day 2: Red-Nosed Reports', () => {
const reportsFilePath = path.join(__dirname, 'reports.txt');

it('Part 1: should determine number of safe reports', async () => {
const expectedNumberOfSafeReports = 660; // Verified for this dataset

const numberOfSafeReports = await determineNumberOfSafeReports(reportsFilePath);

assert.strictEqual(numberOfSafeReports, expectedNumberOfSafeReports);
});

it('Part 2: should determine number of safe reports with problem dampener', async () => {
const expectedNumberOfSafeReportsWithProblemDampener = 689; // Verified for this dataset

const numberOfSafeReports = await determineNumberOfSafeReportsWithProblemDampener(reportsFilePath);

assert.strictEqual(numberOfSafeReports, expectedNumberOfSafeReportsWithProblemDampener);
});
});
111 changes: 111 additions & 0 deletions day-2/day-2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import fs from 'node:fs/promises';

/**
* Read file
*/
const readFile = async (filePath: string): Promise<string> => {
const fileContents = await fs.readFile(filePath, {
encoding: 'utf8',
});
const normalizedFileContents = fileContents.trim().split(/\r?\n/).join('\n');
return normalizedFileContents;
};

/**
* Parse reports
*/
const parseReports = (reportsFileContent: string) => {
return reportsFileContent.split('\n').map((levelsAsString) => {
return levelsAsString.split(' ').map((levelAsString) => {
return parseInt(levelAsString, 10);
});
});
};

/**
* Check whether the given levels are safe
*/
const areLevelsSafe = (levels: Array<number>) => {
// Calculate difference between each adjacent level
const levelDifferences: Array<number> = [];
for (let levelIndex = 0; levelIndex < levels.length - 1; levelIndex++) {
levelDifferences.push(levels[levelIndex] - levels[levelIndex + 1]);
}

// Check whether all level differences are within the safe range
const safeLevelRange = [1, 3];
const areLevelDifferencesWithinSafeRange = levelDifferences.every((levelDifference) => {
return Math.abs(levelDifference) >= safeLevelRange[0] && Math.abs(levelDifference) <= safeLevelRange[1];
});
if (!areLevelDifferencesWithinSafeRange) {
return false; // Early exit
}

// Check whether all level differences continue in one direction (increase or decrease)
const hasAnyPositiveLevelDifferences = levelDifferences.some((levelDiff) => {
return levelDiff > 0;
});
const hasAnyNegativeLevelDifferences = levelDifferences.some((levelDiff) => {
return levelDiff < 0;
});
const doAllLevelsContinueInOneDirection =
(hasAnyPositiveLevelDifferences && !hasAnyNegativeLevelDifferences) ||
(hasAnyNegativeLevelDifferences && !hasAnyPositiveLevelDifferences);
if (!doAllLevelsContinueInOneDirection) {
return false; // Early exit
}

// All good :)
return true;
};

/**
* Part 1: Determine number of safe reports
*/
export const determineNumberOfSafeReports = async (reportsFilePath: string) => {
// Get data
const reportsFileContent = await readFile(reportsFilePath);
const reports = parseReports(reportsFileContent);

// Determine number of safe reports
const numberOfSafeReports = reports.filter((levels) => {
return areLevelsSafe(levels);
}).length;

// Done
return numberOfSafeReports;
};

/**
* Part 2: Determine number of safe reports with problem dampener
*/
export const determineNumberOfSafeReportsWithProblemDampener = async (reportsFilePath: string) => {
// Get data
const reportsFileContent = await readFile(reportsFilePath);
const reports = parseReports(reportsFileContent);

// Determine number of safe reports with problem dampener
const numberOfSafeReportsWithProblemDampener = reports.filter((levels) => {
// Construct levels in all variants (#bruteforce)
const levelVariants = [levels];
for (let levelIndex = 0; levelIndex < levels.length; levelIndex++) {
levelVariants.push([...levels.slice(0, levelIndex), ...levels.slice(levelIndex + 1)]);
}

// Check every variant
let isAnyLevelVariantSafe = false;
for (let levelVariantIndex = 0; levelVariantIndex < levelVariants.length; levelVariantIndex++) {
const isLevelVariantSafe = areLevelsSafe(levelVariants[levelVariantIndex]);
if (isLevelVariantSafe) {
isAnyLevelVariantSafe = true;
break; // Early exit
}
}

// Done
return isAnyLevelVariantSafe;
}).length;

// Done
return numberOfSafeReportsWithProblemDampener;
};
Loading

0 comments on commit 5bec5e7

Please sign in to comment.