Skip to content

Commit

Permalink
chore: cleaned up around 2023 day 10
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexAegis committed Dec 10, 2023
1 parent 51ebb73 commit 93371e7
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 103 deletions.
19 changes: 10 additions & 9 deletions resources/2023/10/example.3.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
..........
.S------7.
.|F----7|.
.||....||.
.||....||.
.|L-7F-J|.
.|..||..|.
.L--JL--J.
..........
FF7FSF7F7F7F7F7F---7
L|LJ||||||||||||F--J
FL-7LJLJ||||||LJL-77
F--JF--7||LJLJ7F7FJ-
L---JF-JLJ.||-FJLJJ7
|F|F-JF---7F7-L7L|7|
|FFJF7L7F-JF7|JL---7
7-L-JL7||F7|L7F-7F7|
L.L7LFJ|||||FJL7||LJ
L7JLJL-JLJLJL--JLJ.L
10 changes: 0 additions & 10 deletions resources/2023/10/example.4.txt

This file was deleted.

5 changes: 5 additions & 0 deletions solutions/typescript/2023/10/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@
"import": "./dist/p2.js",
"default": "./dist/p2.js"
},
"./parse": {
"types": "./src/parse.ts",
"import": "./dist/parse.js",
"default": "./dist/parse.js"
},
"./readme": "./readme.md"
},
"dependencies": {
Expand Down
25 changes: 23 additions & 2 deletions solutions/typescript/2023/10/src/p1.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,35 @@ describe('2023 10 p1', () => {
describe('the input', () => {
it('should solve the input', async () => {
const resources = await loadTaskResources(packageJson.aoc);
expect(p1(resources.input)).toEqual(0);
expect(p1(resources.input)).toEqual(6733);
});
});

describe('example 1', () => {
it('should be solved', async () => {
const resources = await loadTaskResources(packageJson.aoc, 'example.1.txt');
expect(p1(resources.input)).toEqual(0);
expect(p1(resources.input)).toEqual(8);
});
});

describe('example 2', () => {
it('should be solved', async () => {
const resources = await loadTaskResources(packageJson.aoc, 'example.2.txt');
expect(p1(resources.input)).toEqual(23);
});
});

describe('example 2b', () => {
it('should be solved', async () => {
const resources = await loadTaskResources(packageJson.aoc, 'example.2b.txt');
expect(p1(resources.input)).toEqual(22);
});
});

describe('example 3', () => {
it('should be solved', async () => {
const resources = await loadTaskResources(packageJson.aoc, 'example.3.txt');
expect(p1(resources.input)).toEqual(80);
});
});
});
33 changes: 3 additions & 30 deletions solutions/typescript/2023/10/src/p1.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,9 @@
import { Direction, descending, task } from '@alexaegis/advent-of-code-lib';
import { descending, task } from '@alexaegis/advent-of-code-lib';
import packageJson from '../package.json';

const pipeConnectorMap: Record<string, Direction[]> = {
'|': [Direction.NORTH, Direction.SOUTH],
'-': [Direction.WEST, Direction.EAST],
L: [Direction.NORTH, Direction.EAST],
J: [Direction.NORTH, Direction.WEST],
'7': [Direction.SOUTH, Direction.WEST],
F: [Direction.SOUTH, Direction.EAST],
'.': [],
S: [Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST],
};
import { parse } from './parse.js';

export const p1 = (input: string): number => {
const graph = input.toGridGraph({
weighter: (a, b, dir) => {
console.log(a.value, b.value, dir.toString());
const aConnectors = pipeConnectorMap[a.value.toString()];
const bConnectors = pipeConnectorMap[b.value.toString()];
const connection =
(aConnectors?.includes(dir) && bConnectors?.includes(dir.reverse())) ?? false;
return connection ? 1 : 0;
},
connectionFilter: (a, b, dir) => {
console.log(a.value, b.value, dir.toString());
const aConnectors = pipeConnectorMap[a.value.toString()];
const bConnectors = pipeConnectorMap[b.value.toString()];

return (aConnectors?.includes(dir) && bConnectors?.includes(dir.reverse())) ?? false;
},
});
graph.print();
const graph = parse(input);

const animalStart = graph.findNode((node) => node.value === 'S');
if (!animalStart) {
Expand Down
25 changes: 23 additions & 2 deletions solutions/typescript/2023/10/src/p2.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,35 @@ describe('2023 10 p2', () => {
describe('the input', () => {
it('should solve the input', async () => {
const { input } = await loadTaskResources(packageJson.aoc);
expect(p2(input)).toEqual(0);
expect(p2(input)).toEqual(435);
});
});

describe('example 1', () => {
it('should be solved', async () => {
const { input } = await loadTaskResources(packageJson.aoc, 'example.1.txt');
expect(p2(input)).toEqual(0);
expect(p2(input)).toEqual(1);
});
});

describe('example 2', () => {
it('should be solved', async () => {
const { input } = await loadTaskResources(packageJson.aoc, 'example.2.txt');
expect(p2(input)).toEqual(4);
});
});

describe('example 2b', () => {
it('should be solved', async () => {
const { input } = await loadTaskResources(packageJson.aoc, 'example.2b.txt');
expect(p2(input)).toEqual(4);
});
});

describe('example 3', () => {
it('should be solved', async () => {
const { input } = await loadTaskResources(packageJson.aoc, 'example.3.txt');
expect(p2(input)).toEqual(10);
});
});
});
60 changes: 18 additions & 42 deletions solutions/typescript/2023/10/src/p2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,9 @@ import {
GridGraphNode,
task,
type ToString,
type Weighter,
} from '@alexaegis/advent-of-code-lib';
import packageJson from '../package.json';

const pipeConnectorMap: Record<string, Direction[]> = {
'|': [Direction.NORTH, Direction.SOUTH],
'-': [Direction.WEST, Direction.EAST],
L: [Direction.NORTH, Direction.EAST],
J: [Direction.NORTH, Direction.WEST],
'7': [Direction.SOUTH, Direction.WEST],
F: [Direction.SOUTH, Direction.EAST],
'.': [],
S: [Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST],
};
import { parse, weighter } from './parse.js';

export const findPartition = <
T extends ToString = string,
Expand Down Expand Up @@ -132,31 +121,16 @@ export const partitionIntoTwoFromLoop = <
};
};

const weighter: Weighter<GridGraphNode> = (a, b, dir) => {
if (a.value === '.' && b.value === '.') {
return 1;
}

const aConnectors = pipeConnectorMap[a.value.toString()];
const bConnectors = pipeConnectorMap[b.value.toString()];

const connection =
(aConnectors?.includes(dir) && bConnectors?.includes(dir.reverse())) ?? false;
return connection ? 1 : Number.POSITIVE_INFINITY;
};

export const p2 = (input: string): number => {
const og = input.toGridGraph<string>({
weighter,
});

const originalGraph = parse(input);
const liminalNodes = new Set<GridGraphNode>();
const gg = new GridGraph<string>();
for (const ogNode of og.nodeValues) {
// Expanding graph to address liminal space
const graph = new GridGraph<string>();
for (const ogNode of originalGraph.nodeValues) {
for (const { from, to, weight, direction } of Direction.allDirections.map((direction) => ({
...ogNode.neighbours.get(direction),
from: ogNode,
to: og.getNode(ogNode.coordinate.add(direction)),
to: originalGraph.getNode(ogNode.coordinate.add(direction)),
direction,
}))) {
if (to === undefined) {
Expand All @@ -175,37 +149,39 @@ export const p2 = (input: string): number => {

const middle = fromDoubled.middle(toDoubled);

const newFrom = gg.nodes.getOrAdd(
const newFrom = graph.nodes.getOrAdd(
fromDoubled.toString(),
(_n) => new GridGraphNode(fromDoubled, from.value),
);
const newMiddle = gg.nodes.getOrAdd(
const newMiddle = graph.nodes.getOrAdd(
middle.toString(),
(_n) => new GridGraphNode(middle, newNodeSymbol),
);
liminalNodes.add(newMiddle);
const newTo = gg.nodes.getOrAdd(
const newTo = graph.nodes.getOrAdd(
toDoubled.toString(),
(_n) => new GridGraphNode(toDoubled, to.value),
);

newFrom.attachNeightbours(gg, Direction.cardinalDirections, weighter);
newMiddle.attachNeightbours(gg, Direction.cardinalDirections, weighter);
newTo.attachNeightbours(gg, Direction.cardinalDirections, weighter);
newFrom.attachNeightbours(graph, Direction.cardinalDirections, weighter);
newMiddle.attachNeightbours(graph, Direction.cardinalDirections, weighter);
newTo.attachNeightbours(graph, Direction.cardinalDirections, weighter);
}
}

const animalStart = gg.findNode((node) => node.value === 'S');
const animalStart = graph.findNode((node) => node.value === 'S');

if (!animalStart) {
throw new Error('no starting position for the animal!');
}

const pathLoop = gg.flood(animalStart);
const pathLoop = graph.flood(animalStart);

const { inside, outside } = partitionIntoTwoFromLoop(gg, pathLoop);
const { inside, outside } = partitionIntoTwoFromLoop(graph, pathLoop);

gg.print((n) => (inside.has(n) ? 'I' : outside.has(n) ? 'O' : n.toString()));
if (process.env['RUN']) {
graph.print((n) => (inside.has(n) ? 'I' : outside.has(n) ? 'O' : n.toString()));
}

return inside.valueArray().filter((node) => !liminalNodes.has(node)).length ?? -1;
};
Expand Down
35 changes: 35 additions & 0 deletions solutions/typescript/2023/10/src/parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {
Direction,
GridGraphNode,
type GridGraph,
type Weighter,
} from '@alexaegis/advent-of-code-lib';

const pipeConnectorMap: Record<string, Direction[]> = {
'|': [Direction.NORTH, Direction.SOUTH],
'-': [Direction.WEST, Direction.EAST],
L: [Direction.NORTH, Direction.EAST],
J: [Direction.NORTH, Direction.WEST],
'7': [Direction.SOUTH, Direction.WEST],
F: [Direction.SOUTH, Direction.EAST],
'.': [],
S: [Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST],
};

export const weighter: Weighter<GridGraphNode> = (a, b, dir) => {
if (a.value === '.' && b.value === '.') {
return 1;
}

const aConnectors = pipeConnectorMap[a.value.toString()];
const bConnectors = pipeConnectorMap[b.value.toString()];

const connection =
(aConnectors?.includes(dir) && bConnectors?.includes(dir.reverse())) ?? false;
return connection ? 1 : Number.POSITIVE_INFINITY;
};

export const parse = (input: string): GridGraph =>
input.toGridGraph({
weighter,
});
18 changes: 10 additions & 8 deletions solutions/typescript/libs/lib/src/model/graph/graph.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,19 +220,22 @@ export class Graph<
}

/**
*
* A gutted out aStar, not trying to find a path, but calculating a distanceMap
* to all reachable node.
*/
public flood(start: N | undefined, options?: GraphTraversalOptions<N, Dir>): Map<N, number> {
if (!start) {
return new Map();
}
const openSet = new Set<N>([start]); // q?
const cameFrom = new Map<N, N>(); // prev!
const gScore = new Map<N, number>(); // dist! Infinity
const gScore = new Map<N, number>(); // weightMap! Infinity
const dMap = new Map<N, number>(); // distanceMap Infinity

const h = options?.heuristic ?? (() => 1);

gScore.set(start, 0);
dMap.set(start, 0);

const fScore = new Map<N, number>(); // Infinity
fScore.set(start, h(start, []));
Expand All @@ -252,29 +255,28 @@ export class Graph<
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const current = umin.node!;

const currentPath = Graph.generatePath(cameFrom, start, current);

openSet.delete(current);

for (const neighbour of options?.edgeGenerator?.(this.nodes, current, currentPath) ??
current) {
for (const neighbour of options?.edgeGenerator?.(this.nodes, current, []) ?? current) {
const tentativegScore =
(gScore.get(current) ?? Number.POSITIVE_INFINITY) +
(options?.weighter
? options.weighter(neighbour.from, neighbour.to, neighbour.direction)
: neighbour.weight ?? 1);
const tentativeDistance = (dMap.get(current) ?? 0) + 1;
if (tentativegScore < (gScore.get(neighbour.to) ?? Number.POSITIVE_INFINITY)) {
cameFrom.set(neighbour.to, current);
gScore.set(neighbour.to, tentativegScore);
fScore.set(neighbour.to, tentativegScore + h(neighbour.to, currentPath));
fScore.set(neighbour.to, tentativegScore);
dMap.set(neighbour.to, tentativeDistance);
if (!openSet.has(neighbour.to)) {
openSet.add(neighbour.to);
}
}
}
}

return gScore;
return dMap;
}

/**
Expand Down

0 comments on commit 93371e7

Please sign in to comment.