How to draw right triangle using recursion in prolog?

折月煮酒 提交于 2021-01-04 04:34:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!