如何在序言中使用递归绘制直角三角形? [英] How to draw right triangle using recursion in prolog?
问题描述
我得到了这个直角三角形的答案,如下所示:
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?
*
**
***
****
*****
******
推荐答案
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.
我在打印空间时遇到问题.SWI prolog 似乎有一个错误:它要么不打印任何内容,要么打印 ' '
.因此,此代码可能与您的 prolog 解释器一起使用 write(' ')
而不是 write('.')
运行.
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('.')
.
代码与您的非常相似.主要区别在于计数有 3 个参数:迭代器 A
、字符边界数 B
和写入的字符总数 (N
>).迭代器 A
必须小于或等于 N
.根据条件 A >= B
,它会打印 '*'
或 '.'
.另外我必须写它倒数,否则树会颠倒/从左到右.
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.
这篇关于如何在序言中使用递归绘制直角三角形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!