From 6b086acd5b5996b2e8299a10b63d8a9bf8fd4108 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Fri, 7 Dec 2018 21:09:17 -0800 Subject: [PATCH] [2018][ruby][08] speedrun --- 2018/ruby/day_08.rb | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 2018/ruby/day_08.rb diff --git a/2018/ruby/day_08.rb b/2018/ruby/day_08.rb new file mode 100644 index 0000000..7a1faf8 --- /dev/null +++ b/2018/ruby/day_08.rb @@ -0,0 +1,34 @@ +raw = ARGF.read.chomp.split(/\s+/).map(&:to_i) + +class Node + def self.from(raw) + child_count = raw.shift + metadata_count = raw.shift + + children = child_count.times.map { Node.from(raw) } + metadata = metadata_count.times.map { raw.shift } + + Node.new(children, metadata) + end + + def initialize(children, metadata) + @children, @metadata = children, metadata + end + + def checksum + @metadata.sum + @children.map(&:checksum).sum + end + + def value + if @children.empty? + @metadata.sum + else + @metadata.flat_map {|index| + @children.fetch(index-1, []) + }.map(&:value).sum + end + end +end + +root = Node.from(raw) +p root.value