this code using to draw triangle please can any one explain how it work
predicates
star(integer).
count(integer,integer).
clauses
star(1):-write('*'),!.
star(X):-X<=0,!.
star(X):-count(1,X),Z=x-1,nl,star(Z),!.
count(X,Y):-X<=Y,write('*'),X1=X+1,count(X1,Y),!.
count(X<Y):-X>Y,!.
this code draw 5 star ,4,3,2,1
how i doing to begin from 1,2,3,4,5
You must pass around the upper limit:
star :- star(0, 5).
star(C, X) :- C < X, count(0, C), C1 is C+1, star(C1, X).
star(C, X) :- C >= X.
count(X, Y) :- X =< Y, write('*'), X1 is X+1, count(X1,Y).
count(X, Y) :- X > Y, nl.
Change back operators to fit your prolog (i.e. is
become =
, >=
become =>
, etc).
Note that cuts are not mandatory... Use with care.
?- star.
*
**
***
****
*****
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.