How can I draw a star triangle using recursive in the prologue?

this code using a triangle, please can someone explain how it works.

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 stars 4,3,2,1 how do i do to start with 1,2,3,4,5

+4
source share
2 answers

You must pass 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.

Replace the operators with a match for your prolog (i.e., isbecome =, >=become =>, etc.). Note that cuts are optional ... Use with caution.

?- star.
*
**
***
****
*****
+2
source

CapelliC gets credit for the solution, but I will change it a bit for clarity and try 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

: star row_of_stars ( count). star "". , : . row_of_stars ( count) . , . , , , .

+3

All Articles