如何在prolog中使用递归绘制星三角?

时间:2013-11-15 20:17:44

标签: prolog

此代码用于绘制三角形,请任何人解释它是如何工作的

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,!.

此代码绘制5星,4,3,2,1 我怎么做从1,2,3,4,5

开始

2 个答案:

答案 0 :(得分:3)

CapelliC对此解决方案有所帮助,但为了清晰起见,我将稍微调整一下,并尝试添加一些解释:

% 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

使用两个主要谓词解决了此问题:starrow_of_stars(以前为count)。 star谓词在“三角”级别管理问题。也就是说,它专注于行:要打印的行数,以及打印时每行应该获得的星数。另一个谓词row_of_stars(或以前的count)专注于给定数量的恒星的单个行。它只打印出要打印的星星数量。由于问题需要对行以及行中的星数进行递归或迭代,因此将解决方案分解为这两个区域可以简化问题。

答案 1 :(得分:2)

你必须绕过上限:

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.

更改操作符以适合您的序言(即is变为=>=变为=>等。 请注意,削减强制要求......谨慎使用。

?- star.
*
**
***
****
*****