Advertisement
FubFubFub

Day 8

Dec 8th, 2022
873
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.92 KB | Source Code | 0 0
  1. % Our forest
  2. row(1, [3,0,3,7,3]).
  3. row(2, [2,5,5,1,2]).
  4. row(3, [6,5,3,3,2]).
  5. row(4, [3,3,5,4,9]).
  6. row(5, [3,5,3,9,0]).
  7.  
  8. % Predicates to determine first and last row and column
  9. first_row(1).
  10. last_row(LastRow) :- findall(Row, row(Row, _), RowList), max_list(RowList, LastRow).
  11. first_column(1).
  12. last_column(LastColumn) :- row(1, FirstRow), length(FirstRow, LastColumn).
  13.  
  14. % Get the height of the tree at X, Y
  15. tree_height_at(X, Y, Height) :- row(X, RowList), nth(Y, RowList, Height).
  16.  
  17. % Determine if the tree at X, Y is visible. Notice the cut after each match -- if we know one condition is satisfied, we don't have to iterate over the others
  18. % If a tree is in the first or last rows, or the first or last columns, then it is visible.
  19. visible(_, Y) :- first_row(Y), !.
  20. visible(_, Y) :- last_row(Y), !.
  21. visible(X, _) :- first_column(X), !.
  22. visible(X, _) :- last_column(X), !.
  23. % A tree is visible if an adjacent tree is lower than this tree and is itself visible.
  24. visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is X - 1, tree_height_at(A, Y, LeftHeight), LeftHeight < ThisHeight, visible(A, Y), !.
  25. visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is X + 1, tree_height_at(A, Y, LeftHeight), LeftHeight < ThisHeight, visible(A, Y), !.
  26. visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is Y - 1, tree_height_at(X, A, LeftHeight), LeftHeight < ThisHeight, visible(X, A), !.
  27. visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is Y + 1, tree_height_at(X, A, LeftHeight), LeftHeight < ThisHeight, visible(X, A), !.
  28.  
  29. % Make a list of with an item for each visible tree, and count the number of items in the list
  30. solve(VisibleTreeCount) :- first_row(FirstRow), last_row(LastRow), first_column(FirstColumn), last_column(LastColumn), findall(RowCounter, (between(FirstRow, LastRow, RowCounter), between(FirstColumn, LastColumn, ColumnCounter), visible(ColumnCounter, RowCounter)), VisibleTreeList), length(VisibleTreeList, VisibleTreeCount).
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement