From e81de93801ce4ca0e92141588b8b8c38e3adc23a Mon Sep 17 00:00:00 2001 From: Jeremy Kaplan Date: Sun, 15 Dec 2019 12:49:30 -0800 Subject: [PATCH] 2019: Day 15 Part 1 --- 2019/day15/intcode.rb | 244 +++++++++++++++++++++++++++++++++++++ 2019/day15/part1.rb | 271 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 515 insertions(+) create mode 100644 2019/day15/intcode.rb create mode 100644 2019/day15/part1.rb diff --git a/2019/day15/intcode.rb b/2019/day15/intcode.rb new file mode 100644 index 0000000..cee7224 --- /dev/null +++ b/2019/day15/intcode.rb @@ -0,0 +1,244 @@ +# frozen_string_literal: true + +require 'forwardable' + +module Intcode + def self.read(filename) + parse File.read(filename) + end + + def self.parse(input) + parsed = input + .gsub(/^#.*$/, '') + .gsub('\s', '') + .split(',') + .map(&:to_i) + Program.new parsed + end + + class Program + def initialize(mem) + @initial_state = mem + end + + def as_memory + Memory.new(@initial_state.clone) + end + + def run(&user_input) + Computer.new(as_memory).run(&user_input) + end + end + + class Memory + extend Forwardable + + def_delegator :@cells, :[] + def_delegator :@cells, :[]= + + attr_accessor :relative_base + + def initialize(cells) + @cells = cells + @relative_base = 0 + end + + def to_s + batch_size = 10 + s = String.new + @cells.each_slice(batch_size).each_with_index do |batch, idx| + prefix = idx * batch_size + s << "#{prefix}: #{batch.join(' ')}\n" + end + s + end + + def read(addr, mode) + # raise ArgumentError, "address out of range: #{addr}" if addr.negative? || addr >= @cells.length + return 0 if addr.negative? || addr >= @cells.length + + case mode + when INDIRECT_MODE + read(@cells[addr], IMMEDIATE_MODE) + when IMMEDIATE_MODE + @cells[addr] + when RELATIVE_MODE + read(@cells[addr] + relative_base, IMMEDIATE_MODE) + else + raise ArgumentError, "unexpected mode: #{mode}" + end + end + + def write(addr, mode, val) + raise ArgumentError, "address out of range: #{addr}" if addr.negative? || addr >= @cells.length + + case mode + when INDIRECT_MODE + r = @cells[addr] + @cells[r] = val + when IMMEDIATE_MODE + raise ArgumentError, 'writes are not allowed in immediate mode' + @cells[addr] + when RELATIVE_MODE + r = @cells[addr] + relative_base + @cells[r] = val + else + raise ArgumentError, "unexpected mode: #{mode}" + end + end + end + + INDIRECT_MODE = 0 + IMMEDIATE_MODE = 1 + RELATIVE_MODE = 2 + + class Computer + def initialize(mem, &block) + @mem = mem + @ip = 0 + @input_block = block + end + + def on_output(&block) + @output_block = block + end + + def run + loop do + return if tick == :done_executing + end + end + + def tick + opcode = operation(@mem[@ip]) + case opcode + when 1 + add! + nil + when 2 + mul! + nil + when 3 + input!(&@input_block) + nil + when 4 + output!(&@output_block) + when 5 + branch_if_not_zero! + nil + when 6 + branch_if_zero! + nil + when 7 + less_than! + nil + when 8 + equal! + nil + when 9 + move_relative_base! + nil + when 99 + :done_executing + else + raise StandardError, "unexpected opcode: #{opcode}" + end + end + + private + + def add! + mode = modes(@mem[@ip]) + a = @mem.read(@ip + 1, mode[0]) + b = @mem.read(@ip + 2, mode[1]) + @mem.write(@ip + 3, mode[2], a + b) + @ip += 4 + end + + def mul! + mode = modes(@mem[@ip]) + a = @mem.read(@ip + 1, mode[0]) + b = @mem.read(@ip + 2, mode[1]) + @mem.write(@ip + 3, mode[2], a * b) + @ip += 4 + end + + def input!(&user_input) + mode = modes(@mem[@ip]) + inp = input(&user_input) + @mem.write(@ip + 1, mode[0], inp) + @ip += 2 + end + + def output!(&user_output) + mode = modes(@mem[@ip]) + output = @mem.read(@ip + 1, mode[0]) + user_output.call output if block_given? + @ip += 2 + output + end + + def branch_if_not_zero! + mode = modes(@mem[@ip]) + a = @mem.read(@ip + 1, mode[0]) + b = @mem.read(@ip + 2, mode[1]) + @ip = a.zero? ? @ip + 3 : b + end + + def branch_if_zero! + mode = modes(@mem[@ip]) + a = @mem.read(@ip + 1, mode[0]) + b = @mem.read(@ip + 2, mode[1]) + @ip = a.zero? ? b : @ip + 3 + end + + def less_than! + mode = modes(@mem[@ip]) + a = @mem.read(@ip + 1, mode[0]) + b = @mem.read(@ip + 2, mode[1]) + val = a < b ? 1 : 0 + @mem.write(@ip + 3, mode[2], val) + @ip += 4 + end + + def equal! + mode = modes(@mem[@ip]) + a = @mem.read(@ip + 1, mode[0]) + b = @mem.read(@ip + 2, mode[1]) + val = a == b ? 1 : 0 + @mem.write(@ip + 3, mode[2], val) + @ip += 4 + end + + def move_relative_base! + mode = modes(@mem[@ip]) + delta = @mem.read(@ip + 1, mode[0]) + @mem.relative_base += delta + @ip += 2 + end + + def input + if block_given? + inp = yield + raise "Invalid input: #{inp.inspect}" unless inp.is_a?(Numeric) + + return inp + end + + print 'input> ' + gets.to_i + end + + def operation(cell) + (cell % 100) + end + + def modes(cell) + m = Hash.new(0) + (cell / 100).truncate.digits.each_with_index do |d, i| + m[i] = d + end + m + end + end +end diff --git a/2019/day15/part1.rb b/2019/day15/part1.rb new file mode 100644 index 0000000..c2660a5 --- /dev/null +++ b/2019/day15/part1.rb @@ -0,0 +1,271 @@ +# frozen_string_literal: true + +require 'set' +require_relative 'intcode' + +Cell = Struct.new(:x, :y) do + def north + Cell.new(x, y - 1) + end + + def south + Cell.new(x, y + 1) + end + + def west + Cell.new(x - 1, y) + end + + def east + Cell.new(x + 1, y) + end + + def neighbors + [north, south, west, east] + end + + def direction_to(other) + dx = other.x - x + dy = other.y - y + + if dy.negative? + :north + elsif dy.positive? + :south + elsif dx.negative? + :west + elsif dx.positive? + :east + end + end +end + +class Map + def initialize + @grid = {} + end + + def set_content!(cell, content) + @grid[cell] = content + end + + def get(cell) + @grid[cell] + end + + def printable(droid_position) + tl, br = corners(droid_position) + + s = String.new + (tl.y..br.y).each do |y| + (tl.x..br.x).each do |x| + cell = Cell.new(x, y) + s << if cell == droid_position + 'D' + else + char(cell) + end + end + s << "\n" + end + s + end + + def goal + @grid.each_pair do |cell, content| + return cell if content == :oxygen + end + nil + end + + private + + def corners(droid_position) + min_x = max_x = droid_position.x + min_y = max_y = droid_position.y + + @grid.keys.each do |p| + min_x = [min_x, p.x].min + min_y = [min_y, p.y].min + max_x = [max_x, p.x].max + max_y = [max_y, p.y].max + end + + upper_left = Cell.new(min_x, min_y) + lower_right = Cell.new(max_x, max_y) + [upper_left, lower_right] + end + + def char(cell) + content = get(cell) + case content + when :wall + '#' + when :open + '.' + when :oxygen + 'G' + when nil + ' ' + else + raise StandardError, "unknown content: #{content}" + end + end +end + +class Droid + def initialize(program, map) + @computer = Intcode::Computer.new(program.as_memory) { on_input } + @map = map + + @direction = nil + @position = Cell.new(0, 0) + @mode = :exploration + + @map.set_content!(@position, :open) + end + + MOVEMENT_COMMANDS = { north: 1, south: 2, west: 3, east: 4 }.freeze + + def on_input + MOVEMENT_COMMANDS.fetch(@direction) + end + + def run + iterations = 0 + loop do + result = step! + if (iterations % 100).zero? + print_state! + sleep 0.01 + end + + return result if result + + iterations += 1 + end + end + + private + + def step! + case @mode + when :exploration + step_exploration! + nil + when :pathfinding + step_pathfinding + end + end + + def step_pathfinding + search(Cell.new(0, 0), @map.goal) + end + + def step_exploration! + if @path.nil? || @path.length.zero? || @position == @path[-1] || blocked?(@path) + target = closest_unexplored_cell + if target.nil? + # Nothing left to see! + @mode = :pathfinding + return + end + @path = replan(target) + end + + @direction = next_movement + status = next_output! + case status + when 0 + set_content!(@direction, :wall) + # no movement + when 1 + set_content!(@direction, :open) + move!(@direction) + when 2 + set_content!(@direction, :oxygen) + move!(@direction) + else + raise StandardError, "unknown status: #{status}" + end + end + + def next_movement + @path.shift if @position == @path[0] + target = @path[0] + @position.direction_to(target) + end + + def blocked?(path) + path.any? do |cell| + @map.get(cell) == :wall + end + end + + def closest_unexplored_cell + path = bfs( + @position, + ->(cell) { cell.neighbors.reject { |c| @map.get(c) == :wall } }, + ->(cell) { @map.get(cell).nil? }, + ) + path.nil? ? nil : path[-1] + end + + def replan(goal) + search(@position, goal) + end + + def search(start, goal) + bfs( + start, + ->(cell) { cell.neighbors.reject { |c| @map.get(c) == :wall } }, + ->(cell) { cell == goal }, + ) + end + + def move!(direction) + @position = @position.send(direction) + @path.shift if @position == @path[0] + end + + def next_output! + out = nil + out = @computer.tick until out + out + end + + def set_content!(direction, content) + neighbor = @position.send(direction) + @map.set_content!(neighbor, content) + end + + def print_state! + system 'clear' + puts @map.printable(@position) + end +end + +def bfs(start, get_neighbors, is_goal) + queue = [[start]] + visited = Set.new + until queue.empty? + path = queue.shift + state = path[-1] + next if visited.include? state + + visited << state + return path if is_goal.call(state) + + children = get_neighbors.call(state).reject { |cell| visited.include? cell } + children.each do |child| + queue << path + [child] + end + end + nil +end + +program = Intcode.read(File.join(__dir__, 'input')) +map = Map.new +droid = Droid.new(program, map) +path = droid.run +puts path.length - 1