Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

how can i draw star triangle using recursive in prolog?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...