Compare commits

...

3 Commits

Author SHA1 Message Date
Danila Fedorin af8170a3e6 Clean up some solutions. 2020-12-07 23:38:38 -08:00
Danila Fedorin eafb73cfc1 Add day 8 solution. 2020-12-07 21:11:05 -08:00
Danila Fedorin 61713a5faa Add say 7 solution. 2020-12-06 21:35:13 -08:00
3 changed files with 93 additions and 12 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

45
day7.cr Normal file
View File

@ -0,0 +1,45 @@
require "advent"
INPUT = input(2020, 7).lines.map(&.chomp).map do |s|
data = s.match(/^([a-z ]+) bags contain (.*).$/).not_nil!
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|
seen << i[0]
i[1].each do |to|
n, m = to
gr.add_edge(i[0], m, n)
end
end
{seen, gr}
end
def part1
seen, gr = build_graph(INPUT)
seen.count do |s|
gr.find_path(s, "shiny gold") && s != "shiny gold"
end
end
def count_bags(gr, current)
return 1 unless es = gr.@edges[current]?
1 + es.sum do |e|
t, k = e
k * count_bags(gr, t)
end
end
def part2
seen, gr = build_graph(INPUT)
count_bags(gr, "shiny gold") - 1
end
puts part1
puts part2

44
day8.cr Normal file
View File

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