Skip to content

Commit

Permalink
Solve day 6
Browse files Browse the repository at this point in the history
  • Loading branch information
Dlurak committed Dec 6, 2024
1 parent c40fdd2 commit dcdffda
Show file tree
Hide file tree
Showing 10 changed files with 191 additions and 8 deletions.
2 changes: 1 addition & 1 deletion 2024/day01/part1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
words,
mapToInt,
sort,
self,
self,
} from '@helper';

const input = await loadData();
Expand Down
51 changes: 51 additions & 0 deletions 2024/day06/lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { applyOffset, Coordinate } from '@helper';
import { ORTHONAL_OFFSETS } from '@constants';

export type Direction = 'up' | 'down' | 'right' | 'left';

export const nextDirection = (direction: Direction): Direction => {
const mappings: Record<Direction, Direction> = {
up: 'right',
right: 'down',
down: 'left',
left: 'up',
};
return mappings[direction];
};

export const offsetForDirection = (direction: Direction) =>
({
up: ORTHONAL_OFFSETS.bottom,
down: ORTHONAL_OFFSETS.top,
left: ORTHONAL_OFFSETS.left,
right: ORTHONAL_OFFSETS.right,
})[direction];

export const walk = (
matrix: string[][],
current: Coordinate,
currentDirection: Direction,
): [Coordinate, Direction][] => {
const potentialStep = applyOffset(
current,
offsetForDirection(currentDirection),
);
const valueAtNextStep = (matrix[potentialStep.row] ?? [])[potentialStep.col];

if (!valueAtNextStep) {
return [[current, currentDirection]];
}

const direction =
valueAtNextStep === '#'
? nextDirection(currentDirection)
: currentDirection;

const walked = walk(
matrix,
valueAtNextStep === '#' ? current : potentialStep,
direction,
);

return [[current, direction], ...walked];
};
31 changes: 31 additions & 0 deletions 2024/day06/part1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
loadData,
findItemCoordinates,
lines,
uniqueBy,
setValueAtCord,
} from '@helper';
import { walk } from './lib';

const input = await loadData();
const matrix = lines(input, (l) => l.split('') as ('#' | '.' | '^')[]);

const uniqueCoords = uniqueBy(
walk(matrix, findItemCoordinates(matrix, '^')!, 'up'),
([a], [b]) => a.col === b.col && a.row === b.row,
);

if (Bun.env.DATA === 'debug') {
const stringMatrix = uniqueCoords.reduce<string[][]>(
(acc, [coord, dir]) =>
setValueAtCord(
acc,
coord,
{ up: '↑', down: '↓', left: '←', right: '→' }[dir],
),
matrix,
);
console.log(stringMatrix.map((line) => line.join('')).join('\n'));
}

console.log(uniqueCoords.length);
76 changes: 76 additions & 0 deletions 2024/day06/part2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import {
loadData,
applyOffset,
Coordinate,
findItemCoordinates,
lines,
setValueAtCord,
uniqueBy,
} from '@helper';
import { nextDirection, offsetForDirection, walk } from './lib';

type Direction = 'up' | 'down' | 'right' | 'left';

const input = await loadData();
const matrix = lines(input, (l) => l.split('') as ('#' | '.' | '^')[]);

const hasLoop = (
matrix: string[][],
current: Coordinate,
currentDirection: Direction,
visited = new Set<string>(),
): boolean => {
const state = `${current.row},${current.col},${currentDirection}`;
if (visited.has(state)) {
return true;
}
visited.add(state);

const potentialStep = applyOffset(
current,
offsetForDirection(currentDirection),
);
const valueAtNextStep = (matrix[potentialStep.row] ?? [])[potentialStep.col];

if (!valueAtNextStep) {
return false;
}

const direction =
valueAtNextStep === '#'
? nextDirection(currentDirection)
: currentDirection;

return hasLoop(
matrix,
valueAtNextStep === '#' ? current : potentialStep,
direction,
visited,
);
};

const obstacleCoordinates = uniqueBy(
walk(matrix, findItemCoordinates(matrix, '^')!, 'up').map(
([coord, direction]) => {
return applyOffset(coord, offsetForDirection(direction));
},
),
(a, b) => a.col === b.col && a.row === b.row,
);

const loopingMatrixes = obstacleCoordinates.filter((obstacleCord) => {
try {
const newMatrix = setValueAtCord(matrix, obstacleCord, '#');

const loopFound = hasLoop(
newMatrix,
findItemCoordinates(newMatrix, '^')!,
'up',
);
return loopFound;
} catch {
return false;
}
});

console.log(loopingMatrixes.length);
2 changes: 1 addition & 1 deletion constants/offset.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
type Offset = [number, number]

export const ORTHONAL_OFFSETS: Record<string, Offset> = {
export const ORTHONAL_OFFSETS: Record<"top" | "bottom" | "left" | "right", Offset> = {
top: [0, 1],
bottom: [0, -1],
left: [-1, 0],
Expand Down
3 changes: 1 addition & 2 deletions helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ import { loadData } from './loadData';
import { replaceMultiple } from './replaceAll';
import { mapValues } from './objectMap';
import { getKeyByValue } from './getKeyByValue';
import { unique } from './unique';
import { isNum, isDigit } from './isNum';
import { removeConsecutiveNumbers } from './removeConsecutiveNumbers';
import { findAllIndexes } from './findAllIndexes';
import { findDuplicates } from './findDuplicates';
import { lines } from './lines';
import { words } from './words';
export * from './unique';
export * from './sum';
export * from './isSorted';
export * from './quickSelect';
Expand Down Expand Up @@ -54,7 +54,6 @@ export {
replaceMultiple,
mapValues,
getKeyByValue,
unique,
isNum,
isDigit,
removeConsecutiveNumbers,
Expand Down
10 changes: 10 additions & 0 deletions helpers/unique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,13 @@
*/
export const unique = <T extends unknown>(array: T[]): T[] =>
array.filter((value, index, self) => self.indexOf(value) === index);

export const uniqueBy = <T>(arr: T[], isEqual: (val1: T, val2: T) => boolean): T[] => {
return arr.reduce((unique: T[], current: T) => {
const isDuplicate = unique.some((existing) => isEqual(existing, current));
if (!isDuplicate) {
unique.push(current);
}
return unique;
}, []);
};
10 changes: 10 additions & 0 deletions input/2024/day06.debug
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"name": "adventofcode",
"module": "index.ts",
"type": "module",
"devDependencies": {
"bun-types": "latest",
"prettier": "^3.1.0"
Expand All @@ -12,5 +11,6 @@
"scripts": {
"solve": "./runNewest",
"format": "prettier --write ."
}
},
"type": "module"
}
10 changes: 8 additions & 2 deletions tests/helpers/unique.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { expect, test } from 'bun:test';
import { unique } from '@helper';
import { unique, uniqueBy } from '@helper';

test('sum', () => {
test('unique', () => {
expect(unique([1, 1, 1, 1, 1, 1, 2])).toEqual([1, 2]);
expect(unique([])).toEqual([]);
});

test('uniqueBy', () => {
expect(
uniqueBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 1 }], (a, b) => a.a === b.a),
).toEqual([{ a: 1 }, { a: 2 }, { a: 3 }]);
});

0 comments on commit dcdffda

Please sign in to comment.