Prvni priklad s n-arnimi stromy. Cislovani bylo myslim trochu jine. Ohodnoceni se dedi z otce na prvorozeneho syna, pricita se u jeho bratru. Tady je nejaky kod, co jsem zplodil potom doma. Za spravnost nerucim.
Kód: Vybrat vše
% N-arni strom
%
% Zadani:
% Mejme n-arni strom a dane cislo M. Deti jednoho vrcholu jsou cislovany zleva od nuly. Cesta z korene do vrcholu je ohodnocena jako soucet cislovani jednotlivych vrcholu na ceste. Ukolem je vypsat vsechny vrcholy, jejichz cesta ma ohodnoceni prave M.
% --------------------
% Reprezentace dat:
% Vstup: tree(Value,[Children])
% ---------------
% like a DFS with some cutting, if found somewhere
% level(+T,+M,-L)
level(T,M,L):-level(T,0,M,[],L). % wrapper
% check nodes alone
level(t(_,Ch),N,M,In,Out):- % not yet here, continue deeper
N<M, level(Ch,N,M,In,Out).
level(t(V,Ch),M,M,In,[V|Out]):- % found,
level(Ch,M,M,In,Out). % and try its first child, if any
% check lists of node's children
level([],_,_,In,In). % return accumulator
% inside a list
level([Head|Tail],N,M,In,Out):- % not yet here,
N<M, N1 is N+1,
level(Head,N,M,In,Out1), % continue among first's children
level(Tail,N1,M,Out1,Out). % continue among this' brothers
% found in a list
level([t(V,Ch)|_],M,M,In,[V|Out]):- % found
level(Ch,M,M,In,Out). % search among children