CapelliC gets credit for the solution, but I shall tweak it only slightly for clarity and attempt to add some explanation:
% Print a triangle of 1 to N stars
star(N) :- star(1, N). % (I modified this slightly to accept N parameter)
% Print rows of NStars stars up to MaxStars stars
star(NStars , MaxStars ) :-
NStars =< MaxStars , % Print this row if NStars <= MaxStars
row_of_stars(NStars), % Print NStars for this row
NStars1 is NStars+1, % Increment the star count
star(NStars1, MaxStars ). % recursively print NStar1 to MaxStars triangle
star(NStars, MaxStars) :-
NStars > MaxStars . % Done when exceed MaxStars
% Print NumStars stars
row_of_stars(NumStars) :-
row_of_stars(1, NumStars). % Print NumStars starting with star number 1
row_of_stars(N, MaxStars) :-
N =< MaxStars, % This case is if star number doesn't exceed max
write('*'), % Print a star
N1 is N+1, % Increment the star count
print_a_star(N1, MaxStars). % Print the next star in the row
row_of_stars(N, MaxStars) :-
N > MaxStars, nl. % Done when exceed MaxStars
This problem has been broken solved using two main predicates: star
and row_of_stars
(formerly, count
). The star
predicate manages the problem at the "triangle" level. That is, it focuses on rows: how many rows to print, and how many stars each row should get when it's printed. The other predicate, row_of_stars
(or formerly, count
), focuses on a single, row of a given number of stars. It just prints the number of stars it's told to print. Since the problem requires recursing or iterating on rows as well as number of stars in a row, the problem is simplified by breaking the solution into these two areas.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…