gpt4 book ai didi

prolog - 如何在序言中使用递归绘制星形三角形?

转载 作者:行者123 更新时间:2023-12-05 01:06:35 26 4
gpt4 key购买 nike

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

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 开始

最佳答案

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 ),专注于给定数量的星星的单个行。它只是打印它被告知要打印的星数。由于该问题需要对行以及行中的星数进行递归或迭代,因此通过将解决方案分解为这两个区域来简化问题。

关于prolog - 如何在序言中使用递归绘制星形三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20009868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com