Skip to content

Commit

Permalink
Solve day 11
Browse files Browse the repository at this point in the history
  • Loading branch information
Dlurak committed Dec 11, 2024
1 parent fd695ff commit 1dc13cf
Show file tree
Hide file tree
Showing 10 changed files with 128 additions and 16 deletions.
8 changes: 4 additions & 4 deletions 2024/day06/lib.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { applyOffset, Coordinate } from '@helper';
import { applyOffset, Coordinate, valueAtCoord } from '@helper';
import { ORTHONAL_OFFSETS } from '@constants';

export type Direction = 'up' | 'down' | 'right' | 'left';
Expand All @@ -15,8 +15,8 @@ export const nextDirection = (direction: Direction): Direction => {

export const offsetForDirection = (direction: Direction) =>
({
up: ORTHONAL_OFFSETS.bottom,
down: ORTHONAL_OFFSETS.top,
up: ORTHONAL_OFFSETS.top,
down: ORTHONAL_OFFSETS.bottom,
left: ORTHONAL_OFFSETS.left,
right: ORTHONAL_OFFSETS.right,
})[direction];
Expand All @@ -30,7 +30,7 @@ export const walk = (
current,
offsetForDirection(currentDirection),
);
const valueAtNextStep = (matrix[potentialStep.row] ?? [])[potentialStep.col];
const valueAtNextStep = valueAtCoord(matrix, potentialStep);

if (!valueAtNextStep) {
return [[current, currentDirection]];
Expand Down
9 changes: 0 additions & 9 deletions 2024/day09/part2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,6 @@ const files = parsedSizes.map((size, index) => {
const id = index % 2 ? null : Math.floor(index / 2);
return { size, id };
});
/* This is a parser for part1
* eventhough this algorithm is optimized on part 2 it can also solve part 1
* ...double as fast as the designated part 1 algorithm
*
const files = parsedSizes.flatMap((size, index) => {
const id = index % 2 ? null : Math.floor(index / 2);
return Array.from({ length: size }, () => ({ size: 1, id }));
});
*/

type Group = (typeof files)[number];

Expand Down
5 changes: 2 additions & 3 deletions 2024/day10/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ export const getFinalCoords = (
const nextCoord = applyOffset(coord, offset);
return [nextCoord, valueAtCoord(matrix, nextCoord)] as const;
})
.filter(([_, num]) => num === value + 1)
.map(([c]) => c);
.filter(([_, num]) => num === value + 1);

return neighbooringCoords.flatMap((c) => getFinalCoords(matrix, c));
return neighbooringCoords.flatMap(([c]) => getFinalCoords(matrix, c));
};
15 changes: 15 additions & 0 deletions 2024/day11/lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const engraveStone = (stone: number) => {
if (stone === 0) {
return [1];
}
const stoneString = `${stone}`;
if (stoneString.length % 2 === 0) {
const middlePoint = stoneString.length / 2;
return [
parseInt(stoneString.slice(0, middlePoint)),
parseInt(stoneString.slice(middlePoint)),
];
}

return [stone * 2024];
};
29 changes: 29 additions & 0 deletions 2024/day11/part1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { loadData, mapToInt, showVisualization, words } from '@helper';
import { engraveStone } from './lib';

const input = await loadData();
const initialStones = mapToInt(words(input));

const cache = new Map<number, number[]>();

const cachedEngraving = (stone: number) => {
const cached = cache.get(stone);
if (cached) {
return cached;
}

const calculated = engraveStone(stone);
cache.set(stone, calculated);
return calculated;
};

let stones = initialStones;
for (let i = 0; i < 25; i++) {
stones = stones.flatMap(cachedEngraving);
}

if (showVisualization()) {
console.log(stones.join(' '));
}

console.log(stones.length);
36 changes: 36 additions & 0 deletions 2024/day11/part2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
countGroups,
loadData,
mapToInt,
mapValues,
showVisualization,
sum,
mergeObjects,
words,
} from '@helper';
import { engraveStone } from './lib';

const input = await loadData();
const stones = mapToInt(words(input));

function proccessStoneCount(stoneCounts: Record<string | number, number>) {
const counts = Object.entries(stoneCounts).map(([stone, count]) => {
const newStones = engraveStone(parseInt(stone));
return mapValues(countGroups(newStones), (v) => v! * count);
});
return mergeObjects(counts, sum);
}

let counts = countGroups(stones) as Record<number, number>;
for (let i = 0; i < 75; i++) {
counts = proccessStoneCount(counts);
}

if (showVisualization()) {
const stoneGroups = Object.entries(counts).map(([stone, length]) =>
Array.from({ length }, () => stone).join(' '),
);
console.log(stoneGroups.join(' '));
}

console.log(sum(Object.values(counts)));
1 change: 1 addition & 0 deletions helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export * from './removeDoubleWhitespaces';
export * from './transpose';
export * from './countGroups';
export * from './lcm';
export * from './mergeObjects';
export * from './matrix/getCoordinate';
export * from './matrix/getNextToCoordinate';
export * from './matrix/newMatrix';
Expand Down
26 changes: 26 additions & 0 deletions helpers/mergeObjects.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { unique } from './unique';

// TODO: Test and document it
// TODO: preserve key type (numbers are turned to strings)

export function mergeObjects<T>(
objects: Record<string | number, T>[],
conflictResolver: (values: T[]) => T,
) {
const keys = unique(objects.flatMap(Object.keys));

const merged: Record<string, T> = {};

for (const key of keys) {
const initialValues = objects
.filter((obj) => key in obj)
.map((obj) => obj[key]);
const newValue =
initialValues.length === 1
? initialValues[0]
: conflictResolver(initialValues);
merged[key] = newValue;
}

return merged;
}
1 change: 1 addition & 0 deletions input/2024/day11.debug
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
125 17
14 changes: 14 additions & 0 deletions runNewest
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ PART=1
DATA=debug
COPY=false
VIS=false
MEASURE=false

PROJECT_ROOT="$PWD"
while [ ! -f "$PROJECT_ROOT/README.md" ]; do
Expand All @@ -29,6 +30,7 @@ usage() {
echo " -D --data Use real input data or just debug (default: debug) (options: debug solve)"
echo " -c --copy Copy the answer (default: false)"
echo " -v --vis Show cool little visualizations (default: false)"
echo " -m --measure Show cool little visualizations (default: false)"
exit 1
}

Expand Down Expand Up @@ -86,6 +88,10 @@ while [[ $# -gt 0 ]]; do
VIS=true
shift
;;
-m|--measure)
MEASURE=true
shift
;;
*)
usage
;;
Expand Down Expand Up @@ -132,8 +138,16 @@ export PART=$PART
export DATA=$DATA
export VIS=$VIS

start_time=$(date +%s%N)

SOLUTION=$(bun run "$FILE_PATH" "$INPUT_PATH" | tee /dev/tty)

if [ "$MEASURE" == true ]; then
end_time=$(date +%s%N)
elapsed_time=$(( (end_time - start_time) / 1000000 ))
echo "${elapsed_time}ms"
fi

if [ "$COPY" == true ]; then
echo "$SOLUTION" | sed -r 's/\x1B\[[0-9;]*m//g' | wl-copy
fi

0 comments on commit 1dc13cf

Please sign in to comment.