Watch
1
0
Fork
You've already forked advent-of-code
0

Make space for two-digit days

This commit is contained in:
Jeremy Kaplan 2019-12-10 08:44:15 -08:00
commit 07eb60e5e1
29 changed files with 0 additions and 1584 deletions

10
2019/day01/part1.rb Normal file
View file

@ -0,0 +1,10 @@
# frozen_string_literal: true
answer = 0
File.open(File.join(__dir__, 'input')) do |file|
file.readlines.each do |line|
mass = line.to_i
answer += (mass / 3).truncate - 2
end
end
puts answer

24
2019/day01/part2.rb Normal file
View file

@ -0,0 +1,24 @@
# frozen_string_literal: true
def fuel_needed(mass)
[(mass / 3).truncate - 2, 0].max
end
def total_fuel(mass)
fuel = 0
current = mass
while current.positive?
current = fuel_needed(current)
fuel += current
end
fuel
end
fuel = 0
File.open(File.join(__dir__, 'input')) do |file|
file.readlines.each do |line|
mass = line.to_i
fuel += total_fuel(mass)
end
end
puts fuel

29
2019/day02/part1.rb Normal file
View file

@ -0,0 +1,29 @@
# frozen_string_literal: true
program = File.read(File.join(__dir__, 'input'))
def run(mem)
pc = 0
loop do
case mem[pc]
when 1
r1, r2, r3 = mem[pc+1], mem[pc+2], mem[pc+3]
mem[r3] = mem[r1] + mem[r2]
pc += 4
when 2
r1, r2, r3 = mem[pc+1], mem[pc+2], mem[pc+3]
mem[r3] = mem[r1] * mem[r2]
pc += 4
when 99
return
else
raise StandardError, "unexpected opcode: #{opcode}"
end
end
end
mem = program.split(',').map(&:to_i)
mem[1] = 12
mem[2] = 2
run(mem)
puts mem[0]

41
2019/day02/part2.rb Normal file
View file

@ -0,0 +1,41 @@
# frozen_string_literal: true
def run(mem)
pc = 0
loop do
case mem[pc]
when 1
r1, r2, r3 = mem[pc+1], mem[pc+2], mem[pc+3]
mem[r3] = mem[r1] + mem[r2]
pc += 4
when 2
r1, r2, r3 = mem[pc+1], mem[pc+2], mem[pc+3]
mem[r3] = mem[r1] * mem[r2]
pc += 4
when 99
return mem[0]
else
raise StandardError, "unexpected opcode: #{opcode}"
end
end
end
def solve(program)
(0...99).each do |noun|
(0...99).each do |verb|
puts "Trying noun = #{noun}, verb = #{verb} ..."
mem = program.clone
mem[1] = noun
mem[2] = verb
output = run(mem)
puts "Output: #{output}"
if output == 19690720
return [noun, verb, 100*noun + verb]
end
end
end
end
input = File.read(File.join(__dir__, 'input'))
program = input.split(',').map(&:to_i)
puts solve(program)

92
2019/day03/part1.rb Normal file
View file

@ -0,0 +1,92 @@
# frozen_string_literal: true
require 'pp'
input = File.read(File.join(__dir__, 'input'))
def wires(input)
input.lines.map do |line|
wire_points(line.strip.split(','))
end
end
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def inspect
"Point(#{x}, #{y})"
end
def hash
[x, y].hash
end
def eql?(other)
x == other.x && y == other.y
end
def right(dy)
Point.new(x, y + dy)
end
def left(dy)
Point.new(x, y - dy)
end
def down(dx)
Point.new(x - dx, y)
end
def up(dx)
Point.new(x + dx, y)
end
def move(direction, delta)
case direction
when 'U'
up(delta)
when 'D'
down(delta)
when 'L'
left(delta)
when 'R'
right(delta)
else
raise StandardError, "Unexpected move direction: #{direction}"
end
end
def manhattan_distance_to(other)
(x - other.x).abs + (y - other.y).abs
end
end
def wire_points(moves)
pos = Point.new(0, 0)
# NOTE: We don't include the origin in the list of points because that's not
# considered a valid intersection.
points = []
moves.each do |move|
direction = move[0]
delta = move[1..].to_i
delta.times do
pos = pos.move(direction, 1)
points << pos
end
end
points
end
wire1, wire2 = wires(input)
origin = Point.new(0, 0)
intersections = (wire1 & wire2).sort do |p1, p2|
d1 = p1.manhattan_distance_to origin
d2 = p2.manhattan_distance_to origin
d1 - d2
end
pp intersections.first.manhattan_distance_to origin

107
2019/day03/part2.rb Normal file
View file

@ -0,0 +1,107 @@
# frozen_string_literal: true
require 'pp'
input = File.read(File.join(__dir__, 'input'))
def wires(input)
input.lines.map do |line|
wire_points(line.strip.split(','))
end
end
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def inspect
"Point(#{x}, #{y})"
end
def hash
[x, y].hash
end
def eql?(other)
x == other.x && y == other.y
end
def right(dy)
Point.new(x, y + dy)
end
def left(dy)
Point.new(x, y - dy)
end
def down(dx)
Point.new(x - dx, y)
end
def up(dx)
Point.new(x + dx, y)
end
def move(direction, delta)
case direction
when 'U'
up(delta)
when 'D'
down(delta)
when 'L'
left(delta)
when 'R'
right(delta)
else
raise StandardError, "Unexpected move direction: #{direction}"
end
end
def manhattan_distance_to(other)
(x - other.x).abs + (y - other.y).abs
end
end
def wire_points(moves)
pos = Point.new(0, 0)
# NOTE: We don't include the origin in the list of points because that's not
# considered a valid intersection.
points = []
moves.each do |move|
direction = move[0]
delta = move[1..].to_i
delta.times do
pos = pos.move(direction, 1)
points << pos
end
end
points
end
wire1, wire2 = wires(input)
def times(wire)
by_time = {}
wire.each_with_index do |p, t|
by_time[p] = t + 1 unless by_time.key? p
end
by_time
end
t1 = times(wire1)
t2 = times(wire2)
intersections = t1.keys & t2.keys
intersection_times = {}
intersections.each do |p|
intersection_times[p] = t1[p] + t2[p]
end
sorted_intersections = intersection_times.each_pair.sort_by { |_, t| t }
pp sorted_intersections
pp sorted_intersections.first

24
2019/day04/part1.rb Normal file
View file

@ -0,0 +1,24 @@
# frozen_string_literal: true
input = '' # TODO
range = Range.new(*input.split('-').map(&:to_i))
def pairwise(arr)
arr[0...-1].zip(arr[1..])
end
count = range.count do |n|
# 1. All numbers in this range are six digits
# 2. All numbers in this range are in this range
digits = n.digits.reverse
# 3. Two adjacent digits are the same
double = pairwise(digits).any? { |pair| pair.first == pair.last }
# 4. Going from left to right, the digits *never decrease*
monotonic = pairwise(digits).none? { |pair| pair.last < pair.first }
double && monotonic
end
pp count

40
2019/day04/part2.rb Normal file
View file

@ -0,0 +1,40 @@
# frozen_string_literal: true
input = '' # TODO
range = Range.new(*input.split('-').map(&:to_i))
def pairwise(arr)
arr[0...-1].zip(arr[1..])
end
def runs(digits)
runs = []
ref = digits.first
run = ref.to_s
digits[1..].each do |d|
if d == ref
run += d.to_s
else
runs << run
ref = d
run = ref.to_s
end
end
runs << run
end
count = range.count do |n|
# 1. All numbers in this range are six digits
# 2. All numbers in this range are in this range
digits = n.digits.reverse
# 3. Two adjacent digits are the same
double = runs(digits).any? { |run| run.length == 2 }
# 4. Going from left to right, the digits *never decrease*
monotonic = pairwise(digits).none? { |pair| pair.last < pair.first }
double && monotonic
end
pp count

203
2019/day05/intcode.rb Normal file
View file

@ -0,0 +1,203 @@
# 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)
@input = nil
@initial_state = mem
end
def run(&user_input)
mem = Memory.new(@initial_state.clone)
Executor.new(mem).run(&user_input)
end
end
class Memory
extend Forwardable
def_delegator :@cells, :[]
def_delegator :@cells, :[]=
def initialize(cells)
@cells = cells
end
def to_s
batch_size = 10
output = String.new
@cells.each_slice(batch_size).each_with_index do |batch, idx|
prefix = idx * batch_size
output << "#{prefix}: #{batch.join(' ')}\n"
end
output
end
end
class Executor
def initialize(mem)
@mem = mem
@ip = 0
end
def run(&user_input)
loop do
return if tick(&user_input) == :done_executing
end
end
def tick(&user_input)
case operation(@mem[@ip])
when 1
add!
when 2
mul!
when 3
input!(&user_input)
when 4
output!
when 5
branch_if_not_zero!
when 6
branch_if_zero!
when 7
less_than!
when 8
equal!
when 99
:done_executing
else
raise StandardError, "unexpected opcode: #{opcode}"
end
end
private
def add!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a + b
@ip += 4
end
def mul!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a * b
@ip += 4
end
def input!(&user_input)
mode = modes(@mem[@ip])
r = @mem[@ip + 1]
raise StandardError, "unexpected mode: #{mode[0]}" if mode[0] != 0
@mem[r] = input(&user_input)
@ip += 2
end
def output!
mode = modes(@mem[@ip])
output = read(@ip + 1, mode[0])
puts "output: #{output}"
@ip += 2
end
def branch_if_not_zero!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
@ip = a.zero? ? @ip + 3 : b
end
def branch_if_zero!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
@ip = a.zero? ? b : @ip + 3
end
def less_than!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a < b ? 1 : 0
@ip += 4
end
def equal!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a == b ? 1 : 0
@ip += 4
end
def input
print 'input> '
if block_given?
inp = yield
puts inp
return inp
end
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
def param(val, mode)
case mode
when 0
@mem[val]
when 1
val
else
raise StandardError, "unexpected mode: #{mode}"
end
end
def read(addr, mode)
param(@mem[addr], mode)
end
end
end

7
2019/day05/part1.rb Normal file
View file

@ -0,0 +1,7 @@
# frozen_string_literal: true
require_relative 'intcode'
input = File.join(__dir__, 'input')
program = Intcode.read(input)
program.run

7
2019/day05/part2.rb Normal file
View file

@ -0,0 +1,7 @@
# frozen_string_literal: true
require_relative 'intcode'
input = File.join(__dir__, 'input')
program = Intcode.read(input)
program.run { 5 }

63
2019/day06/part1.rb Normal file
View file

@ -0,0 +1,63 @@
# frozen_string_literal: true
require 'set'
class Body
attr_reader :name, :satellites
def initialize(name)
@name = name
@satellites = []
end
def <<(satellite)
@satellites << satellite
end
def inspect
"<Body #{name}, #{satellites.map(&:name).inspect}>"
end
def to_s
name
end
def direct_orbits
@direct_orbits ||= @satellites.length + @satellites.sum(&:direct_orbits)
end
def indirect_orbits(depth = 0)
@indirect_orbits ||= @satellites.sum do |sat|
depth + sat.indirect_orbits(depth + 1)
end
end
@@registry = {}
def self.get_or_create(name)
if @@registry.key? name
@@registry[name]
else
body = new(name)
@@registry[name] = body
end
end
def self.get(name)
@@registry[name]
end
end
def parse(input)
input.lines.map do |line|
center_name, satellite_name = line.strip.split(')')
center = Body.get_or_create center_name
satellite = Body.get_or_create satellite_name
center << satellite
end
Body.get 'COM'
end
input = File.read(File.join(__dir__, 'input'))
com = parse(input)
puts com.direct_orbits + com.indirect_orbits

90
2019/day06/part2.rb Normal file
View file

@ -0,0 +1,90 @@
# frozen_string_literal: true
require 'set'
class Body
attr_reader :name, :satellites
attr_accessor :parent
def initialize(name)
@name = name
@satellites = []
end
def <<(satellite)
@satellites << satellite
satellite.parent = self
end
def inspect
"<Body #{name}, #{satellites.map(&:name).inspect}>"
end
def to_s
name
end
def direct_orbits
@direct_orbits ||= @satellites.length + @satellites.sum(&:direct_orbits)
end
def indirect_orbits(depth = 0)
@indirect_orbits ||= @satellites.sum do |sat|
depth + sat.indirect_orbits(depth + 1)
end
end
@@registry = {}
def self.get_or_create(name)
if @@registry.key? name
@@registry[name]
else
body = new(name)
@@registry[name] = body
end
end
def self.get(name)
@@registry[name]
end
end
def parse(input)
input.lines.map do |line|
center_name, satellite_name = line.strip.split(')')
center = Body.get_or_create center_name
satellite = Body.get_or_create satellite_name
center << satellite
end
end
input = File.read(File.join(__dir__, 'input'))
parse(input)
def find_path(start, goal)
queue = [[start.parent]]
visited = Set.new
visited << start
until queue.empty?
path = queue.shift
state = path[-1]
next if visited.include? state
visited << state
return path if state.satellites.include? goal
children = state.satellites
children << state.parent if state.parent
children.each do |child|
queue << path + [child]
end
end
nil
end
you = Body.get 'YOU'
santa = Body.get 'SAN'
path = find_path(you, santa)
puts path.length - 1

231
2019/day07/intcode.rb Normal file
View file

@ -0,0 +1,231 @@
# 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, :[]=
def initialize(cells)
@cells = cells
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 [](idx)
raise ArgumentError, "index out of range: #{idx}" if idx.negative? || idx >= @cells.length
@cells[idx]
end
def []=(idx, val)
raise ArgumentError, "index out of range: #{idx}" if idx.negative? || idx >= @cells.length
@cells[idx] = val
end
end
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
case operation(@mem[@ip])
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 99
:done_executing
else
raise StandardError, "unexpected opcode: #{opcode}"
end
end
private
def add!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a + b
@ip += 4
end
def mul!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a * b
@ip += 4
end
def input!(&user_input)
mode = modes(@mem[@ip])
r = @mem[@ip + 1]
raise StandardError, "unexpected mode: #{mode[0]}" if mode[0] != 0
@mem[r] = input(&user_input)
@ip += 2
end
def output!(&user_output)
mode = modes(@mem[@ip])
output = 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 = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
@ip = a.zero? ? @ip + 3 : b
end
def branch_if_zero!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
@ip = a.zero? ? b : @ip + 3
end
def less_than!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a < b ? 1 : 0
@ip += 4
end
def equal!
mode = modes(@mem[@ip])
a = read(@ip + 1, mode[0])
b = read(@ip + 2, mode[1])
r = @mem[@ip + 3]
raise StandardError, "unexpected mode: #{mode[2]}" if mode[2] != 0
@mem[r] = a == b ? 1 : 0
@ip += 4
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
def param(val, mode)
case mode
when 0
@mem[val]
when 1
val
else
raise StandardError, "unexpected mode: #{mode}"
end
end
def read(addr, mode)
param(@mem[addr], mode)
end
end
end

61
2019/day07/part1.rb Normal file
View file

@ -0,0 +1,61 @@
# frozen_string_literal: true
require_relative 'intcode'
def inputter(queue)
idx = 0
proc do
input = queue[idx]
idx += 1
input
end
end
class Amplifier
def initialize(memory, phase)
@memory = memory
@phase = phase
end
def amplify(input)
next_input = inputter([@phase, input])
computer = Intcode::Computer.new(@memory) do
inp = next_input.call
# print 'input> '
# puts inp
inp
end
output = nil
computer.on_output do |out|
output = out
end
computer.run
output
end
end
def thrust(program, phases)
a = Amplifier.new(program.as_memory, phases[0]).amplify(0)
b = Amplifier.new(program.as_memory, phases[1]).amplify(a)
c = Amplifier.new(program.as_memory, phases[2]).amplify(b)
d = Amplifier.new(program.as_memory, phases[3]).amplify(c)
e = Amplifier.new(program.as_memory, phases[4]).amplify(d)
e
end
program = Intcode.read(File.join(__dir__, 'input'))
phase_space = [0, 1, 2, 3, 4].permutation(5)
max_thrust = -Float::INFINITY
max_phases = nil
phase_space.each do |phases|
t = thrust(program, phases)
next unless t > max_thrust
max_thrust = t
max_phases = phases
end
pp max_phases
puts max_thrust

68
2019/day07/part2.rb Normal file
View file

@ -0,0 +1,68 @@
# frozen_string_literal: true
require_relative 'intcode'
def inputter(queue)
idx = 0
proc do
input = queue[idx]
idx += 1
input
end
end
class Amplifier
def initialize(memory, phase)
@input_queue = [phase]
@computer = Intcode::Computer.new(memory) { @input_queue.shift }
end
def amplify(input)
@input_queue << input
output = nil
output = @computer.tick until output
output
end
def input(val)
@input_queue << val
end
end
def thrust(program, phases)
a = Amplifier.new(program.as_memory, phases[0])
b = Amplifier.new(program.as_memory, phases[1])
c = Amplifier.new(program.as_memory, phases[2])
d = Amplifier.new(program.as_memory, phases[3])
e = Amplifier.new(program.as_memory, phases[4])
cache = -Float::INFINITY
out1 = a.amplify(0)
loop do
out2 = b.amplify(out1)
out3 = c.amplify(out2)
out4 = d.amplify(out3)
out5 = e.amplify(out4)
return cache if out5 == :done_executing
cache = out5
out1 = a.amplify(out5)
end
end
program = Intcode.read(File.join(__dir__, 'input'))
phase_space = [5, 6, 7, 8, 9].permutation(5)
max_thrust = -Float::INFINITY
max_phases = nil
phase_space.each do |phases|
t = thrust(program, phases)
next unless t > max_thrust
max_thrust = t
max_phases = phases
end
pp max_phases
puts max_thrust

50
2019/day08/part1.rb Normal file
View file

@ -0,0 +1,50 @@
# frozen_string_literal: true
class Layer
attr_reader :width, :height, :pixels
def initialize(width, height, pixels)
@width = width
@height = height
@pixels = pixels
end
def to_s
s = String.new
pixels.each_slice(@width) do |line|
s << line.join('')
s << "\n"
end
s
end
end
class SpaceImage
attr_reader :width, :height, :data
def initialize(width, height, data)
@width = width
@height = height
@data = data.strip.chars.map(&:to_i)
raise ArgumentError, 'bad data' unless (@data.size % (@width * @height)).zero?
end
def layers
return @layers unless @layers.nil?
@layers = []
@data.each_slice(@width * @height) do |layer|
@layers << Layer.new(@width, @height, layer)
end
@layers
end
end
input = File.read(File.join(__dir__, 'input'))
img = SpaceImage.new(25, 6, input)
target_layer = img.layers.min_by do |layer|
layer.pixels.count(&:zero?)
end
ones = target_layer.pixels.count { |p| p == 1 }
twos = target_layer.pixels.count { |p| p == 2 }
puts ones * twos

86
2019/day08/part2.rb Normal file
View file

@ -0,0 +1,86 @@
# frozen_string_literal: true
class Layer
attr_reader :width, :height, :pixels
def initialize(width, height, pixels)
@width = width
@height = height
@pixels = pixels
end
def get_pixel(r, c)
@pixels[r * @width + c]
end
def to_s
s = String.new
pixels.each_slice(@width) do |line|
s << line.join('')
s << "\n"
end
s
end
def to_tty
s = String.new
pixels.each_slice(@width) do |row|
line = row.map do |pixel|
case pixel
when 1
# Unicode full block
"\u2588"
when 0
' '
else
raise ArgumentError, "Unexpected pixel value #{pixel}"
end
end
s << line.join('')
s << "\n"
end
s
end
end
class SpaceImage
attr_reader :width, :height, :data
def initialize(width, height, data)
@width = width
@height = height
@data = data.strip.chars.map(&:to_i)
raise ArgumentError, 'bad data' unless (@data.size % (@width * @height)).zero?
end
def layers
return @layers unless @layers.nil?
@layers = []
@data.each_slice(@width * @height) do |layer|
@layers << Layer.new(@width, @height, layer)
end
@layers
end
def render
pixels = []
@height.times do |r|
@width.times do |c|
pixel = get_pixel(r, c)
pixels << pixel
end
end
Layer.new(@width, @height, pixels)
end
def get_pixel(r, c)
layers.each do |layer|
pixel = layer.get_pixel(r, c)
return pixel if pixel != 2
end
end
end
input = File.read(File.join(__dir__, 'input'))
img = SpaceImage.new(25, 6, input)
puts img.render.to_tty

243
2019/day09/intcode.rb Normal file
View file

@ -0,0 +1,243 @@
# 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!
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

8
2019/day09/part1.rb Normal file
View file

@ -0,0 +1,8 @@
# frozen_string_literal: true
require_relative 'intcode'
program = Intcode.read(File.join(__dir__, 'input'))
computer = Intcode::Computer.new(program.as_memory) { 1 }
computer.on_output { |out| puts out }
computer.run

Some files were not shown because too many files have changed in this diff Show more