Clean up some solutions.

This commit is contained in:
Danila Fedorin 2020-12-07 23:38:26 -08:00
parent eafb73cfc1
commit af8170a3e6
3 changed files with 28 additions and 75 deletions

16
day6.cr
View File

@ -2,20 +2,12 @@ require "advent"
INPUT = input(2020, 6).split("\n\n")
def part1
input = INPUT.clone
answers = input.map do |i|
i.chars.uniq!.count &.ascii_letter?
end
puts answers.sum
INPUT.sum &.chars.uniq!.count(&.ascii_letter?)
end
def part2
input = INPUT.clone
sol = input.map do |i|
i.split("\n").reject(&.empty?).map(&.chars.to_set).reduce { |s1, s2| s1 & s2 }
end
puts(sol.map(&.size).sum)
INPUT.sum &.lines.map(&.chars.to_set).intersect.size
end
part1
part2
puts part1
puts part2

View File

@ -2,18 +2,19 @@ require "advent"
INPUT = input(2020, 7).lines.map(&.chomp).map do |s|
data = s.match(/^([a-z ]+) bags contain (.*).$/).not_nil!
{data[1], data[2].split(", ").map(&.rchop(" bags").rchop(" bag")) }
contents = data[2].split(", ").compact_map do |s|
s.match(/(\d+) (.*) bags?/).try { |m| {m[1].to_i32, m[2]} }
end
{data[1], contents}
end
def build_graph(input)
gr = Graph(String).new
seen = Set(String).new
input.each do |i|
next if i[1] == ["no other"]
seen << i[0]
i[1].each do |to|
n, _, m = to.partition(" ")
n = n.to_i32
n, m = to
gr.add_edge(i[0], m, n)
end
end

78
day8.cr
View File

@ -1,31 +1,7 @@
require "advent"
INPUT = input(2020, 8).lines
def part1
acc = 0
pc = 0
visited = Set(Int32).new
input = INPUT.clone.map do |s|
code, int = s.split(" ")
{code, int.to_i32}
end
loop do
if visited.includes? pc
break
end
visited << pc
code, int = input[pc]
case input[pc][0]
when "acc"
acc += int
pc += 1
when "jmp"
pc += int
when "nop"
pc += 1
end
end
INPUT = input(2020, 8).lines.map do |s|
code, int = s.split(" ")
{code, int.to_i32}
end
def run(prog)
@ -33,50 +9,34 @@ def run(prog)
pc = 0
visited = Set(Int32).new
loop do
if visited.includes? pc
return false
end
return acc if pc >= prog.size
return {:term, acc} if pc >= prog.size
return {:inf, acc} if visited.includes? pc
visited << pc
code, int = prog[pc]
case prog[pc][0]
case code
when "acc"
acc += int
pc += 1
when "jmp"
pc += int
when "nop"
pc += 1
pc += int - 1
end
pc += 1
end
end
def part1
run(INPUT)[1]
end
def part2
input = INPUT.clone.map do |s|
code, int = s.split(" ")
{code, int.to_i32}
end
jnp = [] of Int32
input.each_with_index do |e, i|
op, int = e
jnp << i if op == "jmp" || op == "nop"
end
jnp = INPUT.find_indices { |e| e[0] == "jmp" || e[0] == "nop" }
jnp.each do |i|
prog = input.clone
if prog[i][0] == "jmp"
prog[i] = {"nop", prog[i][1]}
else
prog[i] = {"jmp", prog[i][1]}
end
prog = INPUT.clone
op, int = prog[i]
prog[i] = {op.tr("jmpnop", "nopjmp"), int}
case i = run(prog)
when Bool
next
when Int32
return i
end
code, acc = run(prog)
return acc if code == :term
end
end