Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can you solve this using prolog please! Consider a binary tree defined by the st

ID: 3845996 • Letter: C

Question

Can you solve this using prolog please!

Consider a binary tree defined by the structure node (value, left, right), where value is a number and left and right can be either another node or a number or the atom empty. Write the rule wght (Tree, Weight) that takes as input a tree and returns a weighted sum of all values in the tree. Each value in the tree is summed, but before adding the value to the total it is multiplied by a number which is the depth of the node in the tree. The root value has weight multiplier 1, its children have weight 2, its grandchildren 3, and so on. ? -wght (node (1, 2, 3), N). N = 11. ? - wght (node (1, 5, node (2, 3, 4)), N). N = 36. ? - wght (node(1, node (5, empty, 2) node (2, 3, 4)), N). N = 42. The left hand diagram below illustrates the final test case above, for node (1, node (5, empty, 2), node (2, 3, 4)). The right hand diagram shows the same tree with weightings of 1, 2 and 3 applied to the values. (The empty node is shown as elementof.)

Explanation / Answer

edge(1,2). edge(1,4). edge(1,3). edge(2,3). edge(2,5). edge(3,4). edge(3,5). edge(4,5). % ------ simple path finding in a directed graph % ----- simple exploration path0(A,B, Result) :- path0(A, B, [], Result). path0(A, B, _, [e(A,B)]):- edge(A,B). path0(A, B, Visited, [e(A,X)|Path]):- edge(A, X), dif(X, B), + member(X, Visited), path0(X, B, [A|Visited], Path ). %---- 1. exploration and length path(A, B, _, [e(A,B)], 1):- edge(A,B). path(A, B, Visited, [e(A,X)|Path], Length):- edge(A, X), + member(X, Visited), length(Path, L), % ERR: Path refers to a open list Length is L + 1, path(X, B, [A|Visited], Path, _). % --- 2. not working path2(A,B, Result, Length) :- path2(A, B, [], Result, Length). path2(A, B, [], [e(A,B)], 1):- edge(A,B). path2(A, B, Visited, [e(A,X)|Path], Length):- edge(A, X), dif(X, B), + member(X, Visited), path2(X, B, [A|Visited], Path, Len), Length is Len + 1.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote