20_jurassic_jigsaw.rb
# Selects tiles of the entire grid and orients them correctly.
# Starts from top left, builds top row, builds left column,
# builds out each subsequent row using the left column.
# Fun fact: Can handle any rectangular input, not just squares.
Selects tiles of the entire grid and orients them correctly.
Starts from top left, builds top row, builds left column,
builds out each subsequent row using the left column.
Fun fact: Can handle any rectangular input, not just squares.
Selects tiles of the entire grid and orients them correctly . Starts from top left builds top row builds left column builds out each subsequent row using the left column . Fun fact : Can handle any rectangular input not just squares .
def build_grid(top_left, tiles)
  top_left.make_top_left!
  top_row = build_line(top_left, :right, :row) { |t| t.uniq.size == 2 }
  width = top_row.size
  left_column = build_line(top_left, :bottom, :column) { |t| t.uniq.size == 2 }
  left_column[1..].map { |left|
    lefts_left_border = if left.uniq.size > 1
      candidates = left.uniq.select { |u|
        t, _ = left.neigh[OPPOSITE[u]]
        t != left_column[-2]
      }
      raise "bottom-left corner has #{candidates} for right border" if candidates.size != 1
      candidates[0]
    else
      left.uniq[0]
    end
    build_line(left, OPPOSITE[lefts_left_border], :row, size: width)
  }.unshift(top_row)
end
def build_grid ( top_left , tiles ) top_left . make_top_left! top_row = build_line ( top_left , :right , :row ) { | t | t . uniq . size == 2 } width = top_row . size left_column = build_line ( top_left , :bottom , :column ) { | t | t . uniq . size == 2 } left_column [ 1 .. ] . map { | left | lefts_left_border = if left . uniq . size > 1 candidates = left . uniq . select { | u | t , _ = left . neigh [ OPPOSITE [ u ] ] t != left_column [ - 2 ] } raise "bottom-left corner has #{candidates} for right border" if candidates . size != 1 candidates [ 0 ] else left . uniq [ 0 ] end build_line ( left , OPPOSITE [ lefts_left_border ] , :row , size : width ) } . unshift ( top_row ) end
Selects tiles of the entire grid and orients them correctly.
Selects tiles of the entire grid and orients them correctly .
# height = left_column.size # left_column also includes the top-left corner, but we don't need to rebuild the top row. # We're at the bottom-left corner, need to pick which one is the left border. # The bottom border has a neighbour above (the second-to-last in left column), # so not that one. # otherwise, a left edge has only one unique border.
top_left
<not_specific>
tiles
<not_specific>