Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- % Our forest
- row(1, [3,0,3,7,3]).
- row(2, [2,5,5,1,2]).
- row(3, [6,5,3,3,2]).
- row(4, [3,3,5,4,9]).
- row(5, [3,5,3,9,0]).
- % Predicates to determine first and last row and column
- first_row(1).
- last_row(LastRow) :- findall(Row, row(Row, _), RowList), max_list(RowList, LastRow).
- first_column(1).
- last_column(LastColumn) :- row(1, FirstRow), length(FirstRow, LastColumn).
- % Get the height of the tree at X, Y
- tree_height_at(X, Y, Height) :- row(X, RowList), nth(Y, RowList, Height).
- % 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
- % If a tree is in the first or last rows, or the first or last columns, then it is visible.
- visible(_, Y) :- first_row(Y), !.
- visible(_, Y) :- last_row(Y), !.
- visible(X, _) :- first_column(X), !.
- visible(X, _) :- last_column(X), !.
- % A tree is visible if an adjacent tree is lower than this tree and is itself visible.
- visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is X - 1, tree_height_at(A, Y, LeftHeight), LeftHeight < ThisHeight, visible(A, Y), !.
- visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is X + 1, tree_height_at(A, Y, LeftHeight), LeftHeight < ThisHeight, visible(A, Y), !.
- visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is Y - 1, tree_height_at(X, A, LeftHeight), LeftHeight < ThisHeight, visible(X, A), !.
- visible(X, Y) :- tree_height_at(X, Y, ThisHeight), A is Y + 1, tree_height_at(X, A, LeftHeight), LeftHeight < ThisHeight, visible(X, A), !.
- % Make a list of with an item for each visible tree, and count the number of items in the list
- 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).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement