Day 6.2
This commit is contained in:
@@ -12,6 +12,7 @@ const Node = struct {
|
||||
};
|
||||
|
||||
const Links = std.ArrayList(Link);
|
||||
const NodeList = std.ArrayList(*Node);
|
||||
const Nodes = std.StringHashMap(*Node);
|
||||
|
||||
fn parse(alloc: *std.mem.Allocator, stream: *std.fs.File.InStream.Stream) !Links {
|
||||
@@ -21,7 +22,6 @@ fn parse(alloc: *std.mem.Allocator, stream: *std.fs.File.InStream.Stream) !Links
|
||||
|
||||
while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
|
||||
std.debug.assert(line.len == 7 and line[3] == ')');
|
||||
std.debug.warn("{}\n", line);
|
||||
|
||||
var out: Link = Link{};
|
||||
std.mem.copy(u8, &out.a, line[0..3]);
|
||||
@@ -48,6 +48,22 @@ fn getOrCreateNode(alloc: *std.mem.Allocator, nodes: var, name: [3]u8) !*Node {
|
||||
}
|
||||
}
|
||||
|
||||
fn getParents(alloc: *std.mem.Allocator, node: *Node) !NodeList {
|
||||
var out = NodeList.init(alloc);
|
||||
var n: *Node = node;
|
||||
while (n.parent) |p| {
|
||||
try out.append(p);
|
||||
n = p;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
// Assumes n1 is a parent of n2
|
||||
fn distance(n1: *Node, n2: *Node) u32 {
|
||||
return n2.depth - n1.depth - 1;
|
||||
}
|
||||
|
||||
pub fn main() anyerror!void {
|
||||
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer arena.deinit();
|
||||
@@ -58,8 +74,6 @@ pub fn main() anyerror!void {
|
||||
|
||||
var links = try parse(alloc, stream);
|
||||
|
||||
std.debug.warn("Part 1: {} links\n", links.len);
|
||||
|
||||
// name -> node
|
||||
var nodes = Nodes.init(alloc);
|
||||
|
||||
@@ -76,8 +90,6 @@ pub fn main() anyerror!void {
|
||||
var a = try getOrCreateNode(alloc, &nodes, link.a);
|
||||
var b = try getOrCreateNode(alloc, &nodes, link.b);
|
||||
|
||||
std.debug.warn("\t{} ) {}\n", a.name, b.name);
|
||||
|
||||
std.debug.assert(b.parent == null);
|
||||
b.parent = a;
|
||||
}
|
||||
@@ -99,4 +111,28 @@ pub fn main() anyerror!void {
|
||||
}
|
||||
|
||||
std.debug.warn("Part 1: {}\n", count);
|
||||
|
||||
// We need to find the node that both you and santa have in common
|
||||
|
||||
var you = (nodes.get("YOU") orelse unreachable).value;
|
||||
var san = (nodes.get("SAN") orelse unreachable).value;
|
||||
|
||||
var yP = try getParents(alloc, you);
|
||||
var sP = try getParents(alloc, san);
|
||||
|
||||
var inCommon = NodeList.init(alloc);
|
||||
|
||||
for (yP.toSlice()) |p1| {
|
||||
for (sP.toSlice()) |p2| {
|
||||
if (p1 == p2) try inCommon.append(p1);
|
||||
}
|
||||
}
|
||||
|
||||
std.debug.warn("Part 2: you have {} parents, santa has {}, {} in common\n", yP.count(), sP.count(), inCommon.count());
|
||||
|
||||
for (inCommon.toSlice()) |p| {
|
||||
const d1 = distance(p, you);
|
||||
const d2 = distance(p, san);
|
||||
std.debug.warn("\t{} - ({}) {} ({}) - {}: {}\n", you.name, d1, p.name, d2, san.name, d1 + d2);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user