This commit is contained in:
Yanick Champoux 2023-11-30 10:13:16 -05:00
parent 602d8fd1f9
commit 95754d7b78
6 changed files with 264 additions and 261 deletions

View File

@ -3,7 +3,7 @@ import * as R from "remeda";
import { passthru } from "../08/part1.js";
import { readFile } from "../05/part1.js";
import V from '@yanick/vyktor';
import V from "@yanick/vyktor";
import { createLogger } from "vite";
const readInput = (...args) =>
@ -11,73 +11,68 @@ const readInput = (...args) =>
readFile(...args),
(lines) => lines.split("\n"),
R.compact, // remove last line
R.map(line => line.match(/x=-?.*?y=-?\d+/g).map(str =>
str.match(/-?\d+/g).map(x => parseInt(x))).map(
coords => V(coords)
R.map((line) =>
line
.match(/x=-?.*?y=-?\d+/g)
.map((str) => str.match(/-?\d+/g).map((x) => parseInt(x)))
.map((coords) => V(coords))
)
));
);
export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");
/** @returns [number,number][] */
export const mergeRanges = ( ranges ) => {
return ranges.reduce( (accum,range) => {
if( accum.length === 0 ) return [ range ];
if( R.last( accum )[1] < range[0] ) {
export const mergeRanges = (ranges) => {
return ranges.reduce((accum, range) => {
if (accum.length === 0) return [range];
if (R.last(accum)[1] < range[0]) {
accum.push(range);
}
else {
R.last(accum)[1] = Math.max(
R.last(accum)[1], range[1]
)
} else {
R.last(accum)[1] = Math.max(R.last(accum)[1], range[1]);
}
return accum;
}, [] );
}
export const spy = passthru( x => console.log(x) );
const entriesInRange = (targetLine,entries) => {
entries = R.uniqBy(entries.map(([_,beacon])=>beacon).filter( beacon => beacon?.y === targetLine ), (x) => x.toString());
return range => {
return entries.filter(
entry => (entry.x >= range[0]) && (entry.x <= range[1])
).length
}
}, []);
};
export const unbeaconAtLine = targetLine => entries => R.pipe(
export const spy = passthru((x) => console.log(x));
const entriesInRange = (targetLine, entries) => {
entries = R.uniqBy(
entries
.map(([_, beacon]) => beacon)
.filter((beacon) => beacon?.y === targetLine),
(x) => x.toString()
);
return (range) => {
return entries.filter((entry) => entry.x >= range[0] && entry.x <= range[1])
.length;
};
};
export const unbeaconAtLine = (targetLine) => (entries) =>
R.pipe(
entries,
R.map( ([x,y]) => [ x, x.manhattanDistance(y) ] ),
R.filter(
e => (
( e[0].y - e[1] <= targetLine) &&
( e[0].y + e[1] >= targetLine)
)
),
R.map(
e => {
R.map(([x, y]) => [x, x.manhattanDistance(y)]),
R.filter((e) => e[0].y - e[1] <= targetLine && e[0].y + e[1] >= targetLine),
R.map((e) => {
const l = e[1] - Math.abs(targetLine - e[0].y);
return [
e[0].x - l,
e[0].x + l ]
}
),
return [e[0].x - l, e[0].x + l];
}),
spy,
(ranges) =>
ranges.sort( (a,b) => {
return (a[0] - b[0]) || (a[1]-b[1]);
} )
,
ranges.sort((a, b) => {
return a[0] - b[0] || a[1] - b[1];
}),
spy,
mergeRanges,
spy,
R.sumBy( range => range[1] - range[0] + 1 - entriesInRange(targetLine,entries)(range) )
R.sumBy(
(range) =>
range[1] - range[0] + 1 - entriesInRange(targetLine, entries)(range)
)
);
export default unbeaconAtLine(2000000);

View File

@ -1,63 +1,47 @@
import * as R from "remeda";
import V from '@yanick/vyktor';
import V from "@yanick/vyktor";
import {
spy,
mergeRanges
} from './part1.js';
import { spy, mergeRanges } from "./part1.js";
const unbeaconAtLine = (max,targetLine,already) => entries => R.pipe(
const unbeaconAtLine = (max, targetLine, already) => (entries) =>
R.pipe(
entries,
R.map( ([x,y]) => [ x, x.manhattanDistance(y) ] ),
R.filter(
e => (
( e[0].y - e[1] <= targetLine) &&
( e[0].y + e[1] >= targetLine)
)
),
R.map(
e => {
R.map(([x, y]) => [x, x.manhattanDistance(y)]),
R.filter((e) => e[0].y - e[1] <= targetLine && e[0].y + e[1] >= targetLine),
R.map((e) => {
const l = e[1] - Math.abs(targetLine - e[0].y);
return [
e[0].x - l,
e[0].x + l ]
}
),
return [e[0].x - l, e[0].x + l];
}),
//spy,
(ranges) => [
...ranges, ...already.filter( v => v.y === targetLine ).map(
v => [ v.x,v.x ]
)
...ranges,
...already.filter((v) => v.y === targetLine).map((v) => [v.x, v.x]),
],
(ranges) =>
ranges.sort( (a,b) => {
return (a[0] - b[0]) || (a[1]-b[1]);
} )
,
ranges.sort((a, b) => {
return a[0] - b[0] || a[1] - b[1];
}),
// spy,
R.map(
range => [ Math.max(0,range[0]), Math.min(max,range[1])]
),
mergeRanges,
R.map((range) => [Math.max(0, range[0]), Math.min(max, range[1])]),
mergeRanges
// spy,
// R.sumBy( range => range[1] - range[0] + 1 - entriesInRange(targetLine,entries)(range) )
);
export const findBeacon = max => entries => {
const already = entries.flat()
export const findBeacon = (max) => (entries) => {
const already = entries.flat();
for (let y = 0; y <= max; y++) {
const ranges = unbeaconAtLine(max,y,already)(entries)
if( ranges.length > 1 ) {
return y + 4000000 * (ranges[0][1] +1);
const ranges = unbeaconAtLine(max, y, already)(entries);
if (ranges.length > 1) {
return y + 4000000 * (ranges[0][1] + 1);
}
// return 'bob';
// return 'bob';
// return x * 4000000 + y;
}
}
};
export default findBeacon(4000000);

View File

@ -5,11 +5,11 @@ import part1, { sample, puzzleInput, unbeaconAtLine } from "./part1.js";
import part2, { findBeacon } from "./part2.js";
describe("part 1", () => {
test('readInput', () => {
test("readInput", () => {
expect(sample[0][0].toArray()).toEqual([2, 18]);
});
test('sample', () => {
test("sample", () => {
expect(unbeaconAtLine(10)(sample)).toEqual(26);
});
@ -19,7 +19,7 @@ describe("part 1", () => {
});
describe("part 2", () => {
test('sample', () => {
test("sample", () => {
expect(findBeacon(20)(sample)).toEqual(56000011);
});
test("solution", () => {

View File

@ -1,33 +1,45 @@
import * as R from "remeda";
import u from "updeep";
import Graph from 'graphology';
import { bidirectional } from 'graphology-shortest-path';
import Graph from "graphology";
import { bidirectional } from "graphology-shortest-path";
import { combinations, permutations } from "combinatorial-generators";
import { readFile } from "../05/part1.js";
const parseLine = (line) => {
const { groups } = line.match(/Valve (?<valve>..).*flow rate=(?<flow>\d+).*valves? (?<exits>.*)/);
return [groups.valve, {
exits: groups.exits.split(',').map(x => x.trim()),
flow: parseInt(groups.flow)
}]
}
const { groups } = line.match(
/Valve (?<valve>..).*flow rate=(?<flow>\d+).*valves? (?<exits>.*)/
);
return [
groups.valve,
{
exits: groups.exits.split(",").map((x) => x.trim()),
flow: parseInt(groups.flow),
},
];
};
const readInput = (...args) =>
R.pipe(
readFile(...args),
(lines) => lines.split("\n"),
R.compact, // remove last line
R.map(parseLine),
Object.fromEntries,
Object.fromEntries
);
export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");
function finalSteam(tunnels, graph, minutesLeft, possibilities, location = 'AA', activeSteam = 0) {
function finalSteam(
tunnels,
graph,
minutesLeft,
possibilities,
location = "AA",
activeSteam = 0
) {
//console.log(minutesLeft, totalSteam, itinary);
if (minutesLeft <= 0) return 0;
@ -36,57 +48,51 @@ function finalSteam(tunnels, graph, minutesLeft, possibilities, location = 'AA',
let scores = [];
for ( const next of possibilities ) {
for (const next of possibilities) {
const path = bidirectional(graph, location, next);
//console.log(path);
let time = path.length;
if (time >= minutesLeft) {
scores.push( minutesLeft * activeSteam );
}
else {
scores.push(minutesLeft * activeSteam);
} else {
//console.log({totalSteam, time, activeSteam});
let ts = time * activeSteam;
let as = activeSteam + tunnels[next].flow;
scores.push(
ts + finalSteam(
tunnels, graph, minutesLeft - time,
possibilities.filter( x => x !== next ),
ts +
finalSteam(
tunnels,
graph,
minutesLeft - time,
possibilities.filter((x) => x !== next),
next,
as
)
)
);
}
}
}
return Math.max( ...scores );
return Math.max(...scores);
}
export const buildGraph = tunnels => {
export const buildGraph = (tunnels) => {
const graph = new Graph();
Object.keys(tunnels).forEach(x => graph.addNode(x));
Object.keys(tunnels).forEach((x) => graph.addNode(x));
Object.entries(tunnels).forEach(([location, { exits }]) => {
exits.forEach(exit => graph.addEdge(location, exit));
exits.forEach((exit) => graph.addEdge(location, exit));
});
return graph;
};
export default (tunnels) => {
const possibilities =
Object.keys(tunnels).filter(
k => tunnels[k].flow
);
const possibilities = Object.keys(tunnels).filter((k) => tunnels[k].flow);
const graph = buildGraph(tunnels);
return finalSteam(tunnels, graph, 30, possibilities, 'AA', 0, 0)
return finalSteam(tunnels, graph, 30, possibilities, "AA", 0, 0);
};

View File

@ -1,16 +1,23 @@
import { bidirectional } from 'graphology-shortest-path';
import { bidirectional } from "graphology-shortest-path";
import * as R from "remeda";
import u from 'updeep';
import u from "updeep";
import { buildGraph } from './part1.js';
import { buildGraph } from "./part1.js";
const findMaxSteam = (tunnels,graph, minutesLeft, unopened, opened, activeSteam, peeps ) => {
const findMaxSteam = (
tunnels,
graph,
minutesLeft,
unopened,
opened,
activeSteam,
peeps
) => {
console.log({ unopened, activeSteam, minutesLeft });
console.log({ unopened, activeSteam, minutesLeft});
let next = R.sortBy(peeps, R.prop("eta"));
let next = R.sortBy(peeps, R.prop('eta'));
if( next[0].eta > minutesLeft ) {
if (next[0].eta > minutesLeft) {
return minutesLeft * activeSteam;
}
@ -20,67 +27,79 @@ const findMaxSteam = (tunnels,graph, minutesLeft, unopened, opened, activeSteam,
const base = delta * activeSteam;
minutesLeft -= delta;
activeSteam += tunnels[ next[0].destination ].flow;
opened = [ ...opened, next[0].destination ];
activeSteam += tunnels[next[0].destination].flow;
opened = [...opened, next[0].destination];
next = u.updateIn( '1.eta', eta => eta - delta, next );
next = u.updateIn("1.eta", (eta) => eta - delta, next);
const scores = [];
let nothing = true;
for ( const destination of unopened ) {
const path = bidirectional(graph, location, destination );
for (const destination of unopened) {
const path = bidirectional(graph, location, destination);
if( path.length > minutesLeft) {
if (path.length > minutesLeft) {
continue;
}
nothing = false;
next = u.updateIn( '0', {
next = u.updateIn(
"0",
{
location,
eta: path.length,
destination
},next);
destination,
},
next
);
scores.push( findMaxSteam(tunnels,graph,minutesLeft,
unopened.filter( x => x !== destination ),
opened, activeSteam, next
) );
scores.push(
findMaxSteam(
tunnels,
graph,
minutesLeft,
unopened.filter((x) => x !== destination),
opened,
activeSteam,
next
)
);
}
if( nothing ) {
next = u.updateIn( '0', {
if (nothing) {
next = u.updateIn(
"0",
{
location,
eta: 999,
destination: 'END',
},next);
destination: "END",
},
next
);
scores.push( findMaxSteam(tunnels,graph,minutesLeft,
scores.push(
findMaxSteam(
tunnels,
graph,
minutesLeft,
unopened,
opened, activeSteam, next
) );
opened,
activeSteam,
next
)
);
}
return base + Math.max( ...scores );
}
return base + Math.max(...scores);
};
export default (tunnels) => {
const possibilities =
Object.keys(tunnels).filter(
k => tunnels[k].flow
);
const possibilities = Object.keys(tunnels).filter((k) => tunnels[k].flow);
const graph = buildGraph(tunnels);
return findMaxSteam(tunnels, graph, 26, possibilities,[],0, [
{ destination: 'AA', eta: 0 },
{ destination: 'AA', eta: 0 },
])
return findMaxSteam(tunnels, graph, 26, possibilities, [], 0, [
{ destination: "AA", eta: 0 },
{ destination: "AA", eta: 0 },
]);
};

View File

@ -5,20 +5,19 @@ import part1, { sample, puzzleInput } from "./part1.js";
import part2 from "./part2.js";
describe("part 1", () => {
test( "input", ()=> {
expect(sample).toMatchObject({AA: {
exists: [
'DD', 'II', 'BB',
],
test("input", () => {
expect(sample).toMatchObject({
AA: {
exists: ["DD", "II", "BB"],
flow: 0,
}})
} )
},
});
});
test("sample", () => {
expect(part1(sample)).toEqual(1651);
});
test("solution", () => {
const r= part1(puzzleInput);
const r = part1(puzzleInput);
expect(r).toBeGreaterThan(707);
expectSolution(part1(puzzleInput)).toEqual(1871);
});