-2

I'm learning prolog in a course. I've been given a question similar to this one, and I also got the same problem (in which it doesnt produce all solutions),

any idea why, will using cuts help? thanks in advance

EDIT: The exercise I've been given is to generate all possible max independent sets from a binary tree. In the second part of the question, I get an integer binary tree, from which i need to get all the mis's, and from those i need to get the one with the maximum on adding its numbers. i.e. if i have a mis with 1,3,9 and a mis with 1,3,4 - i'll return the one with 1,3,9.

Community
  • 1
  • 1
Ariel Pinchover
  • 654
  • 3
  • 17

1 Answers1

1

I changed a little bit the solution from the link ,so it's not entirely my solution it is just the code corrected and i think now it's working fine :

   mis(Tree, List, N) :-
    mis_no_root(Tree, List1, N1),       
    mis_with_root(Tree, List2, N2),!, 
    max_set(List1, N1, List2, N2, List, N). 


max_set(List1, N1, List2, N2, List, N) :-
    (N1>N2,List=List1,N=N1;              
     N2>N1,List=List2,N=N2;
    N2=:=N1,N=N1,(List=List1;List=List2)).              


mis_no_root(nil, [], 0).            
mis_no_root(t(L,_,R), List, N) :-
    mis(L, LeftList, LeftN),        
    mis(R, RightList, RightN),      
    append(LeftList, RightList, List),      
    N is LeftN + RightN.        


mis_with_root(nil, [], 0).          

mis_with_root(t(L,Root,R), [Root|List], N) :-
    mis_no_root(L, LeftList, LeftN),
    mis_no_root(R, RightList, RightN), 
    append(LeftList, RightList, List),      
    N is LeftN + RightN + 1. 

If you want to return one list with solutions you could write:

final_mis(Tree,List,N):-findall(L,mis(Tree, L,_),List),List=[H|_],length(H,N).
coder
  • 12,832
  • 5
  • 39
  • 53
  • why/how did you know to use the cut after mis_with_root in mis? – Ariel Pinchover Aug 28 '16 at 21:03
  • First of all the problem was on the max_set when Ni=N2 to generate all the solutions needed (List=List1;List=List2) while before had List=List1 only .After that i saw that via backtracking was checking and producing duplicate solutions due to max_set predicate so I tried to put ! before max_set (surely ! was going after mis_with_root because we don't want to cut any cases from mis_with_root). – coder Aug 28 '16 at 21:16