Skip to content

Instantly share code, notes, and snippets.

@jacortinas
Last active December 6, 2021 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacortinas/15630fe48be3ee1a7327de6bc9bb2344 to your computer and use it in GitHub Desktop.
Save jacortinas/15630fe48be3ee1a7327de6bc9bb2344 to your computer and use it in GitHub Desktop.
Lazy AOC 2021
# No gems, just plain Ruby 3. Assumes inputs are in an inputs folder or something.
# Each line is a line or multiline input in an IRB prompt.
# Day 1
values = IO.readlines("inputs/1.txt").map(&:to_i)
# Part 1
values.each_cons(2).filter_map { |(a, b)| b > a }.count
# Part 2
values.each_cons(3).each_slice(2).flat_map { |(a, b)| [a.sum, b.sum] }.each_cons(2).filter_map { |(a, b)| b > a }.count
# ----
# Day 2
values = IO.readlines("inputs/2.txt")
# Part 1
totals = values.map { |v| v.split(" ") }.each.with_object(Hash.new(0)) { |v, o| o[v[0]] += v[1].to_i }
totals["forward"] * (totals["down"] - totals["up"])
# Part 2
totals = values.each.with_object({x: 0, y: 0, a: 0}) do |s, o|
i, v = s.split(" ", 2)
v = v.to_i
case i
when "forward"
o[:x] += v
o[:y] += v * o[:a]
when "up"
o[:a] -= v
when "down"
o[:a] += v
end
end
totals[:x] * totals[:y]
# ---
# Day 3
values = IO.readlines("inputs/3.txt", chomp: true).map { |v| v.chars.map(&:to_i) }
# Part 1
g = values.transpose.map { |v| v.sum > (v.size / 2.0) ? 1 : 0 }
e = g.map { |v| v.zero? ? 1 : 0 }
g.join.to_i(2) * e.join.to_i(2)
# Part 2
def search(data:, bit_criteria:, index: 0)
counts = data.transpose[index].tally
digit =
if bit_criteria == :o2
counts[0].to_i <= counts[1].to_i ? 1 : 0
else
counts[0].to_i <= counts[1].to_i ? 0 : 1
end
data = data.select do |val|
val[index] == digit
end
return data.first if data.one?
search(data: data, bit_criteria: bit_criteria, index: index + 1)
end
o2 = search(data: values, bit_criteria: :o2)
co2 = search(data: values, bit_criteria: :co2)
puts o2.join.to_i(2) * co2.join.to_i(2)
# ---
# Day 4
# Part 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment