day10: part2: simplify

This commit is contained in:
Johannes Loher 2020-12-10 14:31:32 +01:00
parent ddcb8b25a9
commit acf28cb71a

View file

@ -1,13 +1,25 @@
import std; import std;
alias Unit = void[0];
alias Set(T) = Unit[T];
auto toSet(R)(R r)
{
return r.map!(element => tuple(element, Unit.init)).assocArray;
}
auto setOf(T)(T[] elements...)
{
return elements.toSet;
}
void main() void main()
{ {
auto nodes = File("input", "r").byLine.map!(to!int).chain([0]) auto nodes = File("input", "r").byLine.map!(to!int).chain([0]).toSet;
.map!(it => tuple(it, cast(void[0])[])).assocArray;
nodes.calculateNumberOfPathsLeadingFromTo(0, nodes.byKey.maxElement).writeln; nodes.calculateNumberOfPathsLeadingFromTo(0, nodes.byKey.maxElement).writeln;
} }
ulong calculateNumberOfPathsLeadingFromTo(void[0][int] nodes, int start, int end) ulong calculateNumberOfPathsLeadingFromTo(Set!int nodes, int start, int end)
{ {
if (end == start) if (end == start)
{ {
@ -20,14 +32,13 @@ ulong calculateNumberOfPathsLeadingFromTo(void[0][int] nodes, int start, int end
unittest unittest
{ {
void[0][int] input = [0 : [], 1 : []]; Set!int input = setOf(0, 1);
assert(input.calculateNumberOfPathsLeadingFromTo(0, 1) == 1); assert(input.calculateNumberOfPathsLeadingFromTo(0, 1) == 1);
} }
unittest unittest
{ {
auto input = [16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4].chain([0]) auto input = [16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4].chain([0]).toSet;
.map!(it => tuple(it, cast(void[0])[])).assocArray;
assert(input.calculateNumberOfPathsLeadingFromTo(0, input.byKey.maxElement) == 8); assert(input.calculateNumberOfPathsLeadingFromTo(0, input.byKey.maxElement) == 8);
} }
@ -36,6 +47,6 @@ unittest
auto input = [ auto input = [
28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11, 28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11,
1, 32, 25, 35, 8, 17, 7, 9, 4, 2, 34, 10, 3 1, 32, 25, 35, 8, 17, 7, 9, 4, 2, 34, 10, 3
].chain([0]).map!(it => tuple(it, cast(void[0])[])).assocArray; ].chain([0]).toSet;
assert(input.calculateNumberOfPathsLeadingFromTo(0, input.byKey.maxElement) == 19_208); assert(input.calculateNumberOfPathsLeadingFromTo(0, input.byKey.maxElement) == 19_208);
} }