passing back answers in prolog
Posted
by
AhmadAssaf
on Stack Overflow
See other posts from Stack Overflow
or by AhmadAssaf
Published on 2011-01-02T00:49:20Z
Indexed on
2011/01/02
0:54 UTC
Read the original article
Hit count: 185
i have this code than runs perfectly .. returns a true .. when tracing the values are ok .. but its not returning back the answer .. it acts strangely when it ends and always return empty list .. uninstantiated variable ..
test :- extend(4,12,[4,3,1,2],[[1,5],[3,4],[6]],_ExtendedBins).
%printing basic information about the
extend(NumBins,Capacity,RemainingNumbers,BinsSoFar,_ExtendedBins) :-
getNumberofBins(BinsSoFar,NumberOfBins),
msort(RemainingNumbers,SortedRemaining),nl,
format("Current Number of Bins is :~w\n",[NumberOfBins]),
format("Allowed Capacity is :~w\n",[Capacity]),
format("maximum limit in bin is :~w\n",[NumBins]),
format("Trying to fit :~w\n\n",[SortedRemaining]),
format("Possible Solutions :\n\n"),
fitElements(NumBins,NumberOfBins,
Capacity,SortedRemaining,BinsSoFar,[]).
%this is were the creation for possibilities will start
%will check first if the number of bins allowed is less than then
%we create a new list with all the possible combinations
%after that we start matching to other bins with capacity constraint
fitElements(NumBins,NumberOfBins,
Capacity,RemainingNumbers,Bins,ExtendedBins) :-
( NumberOfBins < NumBins ->
print('Creating new set: ');
print('Sorry, Cannot create New Sets')),
createNewList(Capacity,RemainingNumbers,Bins,ExtendedBins).
createNewList(Capacity,RemainingNumbers,Bins,ExtendedBins) :-
createNewList(Capacity,RemainingNumbers,Bins,[],ExtendedBins),
print(ExtendedBins).
createNewList(0,Bins,Bins,ExtendedBins,ExtendedBins).
createNewList(_,[],_,ExtendedBins,ExtendedBins).
createNewList(Capacity,[Element|Rest],Bins,Temp,ExtendedBins) :-
conjunct_to_list(Element,ListedElement),
append(ListedElement,Temp,NewList),
sumlist(NewList,Sum),
(Sum =< Capacity,
append(ListedElement,ExtendedBins,Result);
Capacity = 0),
createNewList(Capacity,Rest,Bins,NewList,Result).
fit(0,[],ExtendedBins,ExtendedBins).
fit(Capacity,[Element|Rest],Bin,ExtendedBins) :-
conjunct_to_list(Element,Listed),
append(Listed,Bin,NewBin),
sumlist(NewBin,Sum),
(Sum =< Capacity -> fit(Capacity,Rest,NewBin,ExtendedBins);
Capacity = 0,
append(NewBin,ExtendedBins,NewExtendedBins),
print(NewExtendedBins),
fit(0,[],NewBin,ExtendedBins)).
%get the number of bins provided
getNumberofBins(List,NumberOfBins) :-
getNumberofBins(List,0,NumberOfBins).
getNumberofBins([],NumberOfBins,NumberOfBins).
getNumberofBins([_List|Rest],TempCount,NumberOfBins) :-
NewCount is TempCount + 1, %calculate the count
getNumberofBins(Rest,NewCount,NumberOfBins). %recursive call
%Convert set of terms into a list - used when needed to append
conjunct_to_list((A,B), L) :-
!,
conjunct_to_list(A, L0),
conjunct_to_list(B, L1),
append(L0, L1, L).
conjunct_to_list(A, [A]).
Greatly appreciate the help
© Stack Overflow or respective owner