我必须定义prolog金字塔(N),它打印出一个给定高度的星号金字塔,如下例所示。
pyramid(4).
*
***
*****
*******
true
这是我到目前为止所做的...... 我无法找到打印出每条线所需的其余星星的方法。 我还尝试定义支持谓词来处理程序的子部分。但是找不到它。
pyramid(0) :-
nl.
pyramid(N) :-
N > 0,
N1 is N - 1,
foreach(between(1,N1,_), write(' ')),
write('*'), nl,
pyramid(N1).
答案 0 :(得分:0)
想想每个等级在N
方面有多少个星星。假设你在i
行,N = 4。
N-1
)个空格,一个星号和另外3个空格。i
行获得(N - 1) - (i - 1)
个空格,1 + 2 * (i - 1)
个星标和另一个(N - 1) - (i - 1)
个空格。所以这给了:
pyramid(N) :- pyramid(N, N-1).
pyramid(0, _) :- nl.
pyramid(N, K) :- N > 0, N1 is N - 1,
foreach(between(1, N1, _), write(' ')),
Q is 2 * (K - N1) + 1,
foreach(between(1, Q, _), write('*')),
foreach(between(1, N1, _), write(' ')),
nl, pyramid(N1, K).
我认为(但不确定)您也可以删除N > 0
位,因为首先会检查案例pyramid(0, _)
。
答案 1 :(得分:0)
你应该这样做:
pyramid(N) :- % to make an ASCII art pyramid...
N > 0 , % - if first has to have a height,
pyramid( N-1 , 1 ). % - then just invoke the helper predicate.
. %
pyramid(I,_) :- % If the indentation level has dropped below zero, we're done.
I < 0 . %
pyramid(I,C) :- % otherwise...
I >= 0 , % - if the indentation level is non-negative...
repeat_write(I,' ') , % - write that many spaces,
repeat_write(C,'*') , % - write the desired number of asterix characters
nl , % - a new line,
I1 is I-1 , % - decrement the indentation level
C1 is C+2 , % - increment the asterix count
pyramid(I1,C1). % - and recurse down.
repeat_write(0,_) . % writing zero characters is easy.
repeat_write(N,C) :- % writing N characters is also easy:
N > 0 , % - N must be positive
write(C), % - write a single character
N1 is N-1 , % - decrement N
repeat_write(N1,C). % - recurse down.