re: AoC Day 3: No Matter How You Slice It VIEW POST

FULL DISCUSSION
 

Part 1 and 2 in 25 lines of brute force Ruby:

CLAIM_REGEX =
  /#(?<id>\d+) @ (?<offset_x>\d+),(?<offset_y>\d+): (?<delta_x>\d+)x(?<delta_y>\d+)/.freeze

claims = DATA.readlines
claim_squares = Hash.new { |h, k| h[k] = [] }
fabric_squares = Hash.new(0)

claims.each do |claim|
  match = claim.match(CLAIM_REGEX)
  values = match.names.map(&:to_sym).zip(match.captures.map(&:to_i)).to_h

  (values[:offset_x].next..values[:offset_x] + values[:delta_x]).each do |x|
    (values[:offset_y].next..values[:offset_y] + values[:delta_y]).each do |y|
      coordinates = [x, y]
      claim_squares[values[:id]] << coordinates
      fabric_squares[coordinates] += 1
    end
  end
end

puts(fabric_squares.count { |_, v| v > 1 })

puts claim_squares.lazy.find { |_, squares|
  squares.all? { |square| fabric_squares[square] == 1 }
}.first


__END__
#1 @ 604,100: 17x27
#2 @ 861,26: 23x24
#3 @ 875,844: 29x20
#4 @ 524,114: 24x24
#5 @ 696,820: 26x19
...

Still runs reasonably fast though:

→ time ruby solution.rb
115348
188
ruby solution.rb  0.93s user 0.12s system 98% cpu 1.067 total
 

Wow, this is really clear and nice! Ruby has so. Many. Convenience methods that I really miss when I go to other languages sometimes.

 

Indeed :-) Of course this isn't really code I'd write for a production app, but I have to do that all day anyway... For me the purpose of AoC is recreational programming, i.e. having fun, exploring and just doing things because you can.

code of conduct - report abuse