问题
I get the answer for this right triangle as shown below:
shape:- shape(0, 6).
shape(S, A) :- S < A,
count(0, S),
S1 is S+1,
shape(S1, A).
shape(S, X) :- S >= X.
count(A, B) :- A =< B,
write('*'),
A1 is A+1,
count(A1,B).
count(A, B) :- A > B, nl.
*
**
***
****
*****
******
What should i modify to print the right triangle of this type?
*
**
***
****
*****
******
回答1:
shape(S, _) :- S =< 0.
shape(S, N) :- S > 0,
S1 is S-1,
count(0, S1, N),
shape(S1, N).
count(A, _, N) :- A >= N, nl.
count(A, B, N) :- A < N,
( A >= B
-> write('*')
; write('.')
),
A1 is A+1,
count(A1,B, N).
?- shape(6, 6).
.....*
....**
...***
..****
.*****
******
true ;
false.
I have trouble printing the space. There seems to be a bug with SWI prolog: it either prints nothing or ' '
. So maybe this code runs with your prolog interpreter with write(' ')
instead of write('.')
.
The code is very similar to yours. The main difference is there are 3 parameters for the count: an iterator A
, a character boundary number B
and the total number of characters written (N
). The iterator A
has to be smaller or equal to N
. Depending on the condition A >= B
it either prints '*'
or '.'
. Also I had to write it counting backwards, otherwise the tree would have been upside down / left to right.
来源:https://stackoverflow.com/questions/65277514/how-to-draw-right-triangle-using-recursion-in-prolog