Home > Archive > Prolog > June 2007 > Outputting a triangle in Prolog?
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Outputting a triangle in Prolog?
|
|
| Peppy 2007-05-16, 10:04 pm |
| I am trying to write a prolog predicate triangle which finds the
number of balls in a triangle of base N and then draws the triangle
using write('o') to draw a ball. (I'm using Win Prolog)
e.g. if you run...
?-triangle(4).
you should get...
6 balls
o
oo
ooo
I get the first part right but I can't get any more than one line of
balls to appear using my code...
triangle(X):-X>0,
C is X * (X + 1) / 2,
write(C),write(' balls'),nl,
drawlines(X,C),nl.
drawlines(X,C):- C>0,drawball(X),drawlines(X-1,C-X),nl. %draws N
balls and then N-1 balls etc.
drawball(X):- X>0,write('o'),drawball(X-1).
Any help would be gratefully received as this was given as a sample
question for an exam I've tomorrow!
As far as I know it can be implemented at least 2 ways - 1 with lists
and 1 without lists.
thanks,
Peppy.
| |
| Geoffrey Summerhayes 2007-05-17, 7:06 pm |
| On May 16, 8:07 pm, Peppy <BrenOMah...@gmail.com> wrote:
> I am trying to write a prolog predicate triangle which finds the
> number of balls in a triangle of base N and then draws the triangle
> using write('o') to draw a ball. (I'm using Win Prolog)
>
> e.g. if you run...
> ?-triangle(4).
>
> you should get...
>
> 6 balls
> o
> oo
> ooo
>
> I get the first part right but I can't get any more than one line of
> balls to appear using my code...
>
> triangle(X):-X>0,
> C is X * (X + 1) / 2,
> write(C),write(' balls'),nl,
> drawlines(X,C),nl.
>
> drawlines(X,C):- C>0,drawball(X),drawlines(X-1,C-X),nl. %draws N
> balls and then N-1 balls etc.
>
> drawball(X):- X>0,write('o'),drawball(X-1).
Your output is upside down from your example and the
newline in drawlines/1 is in the wrong place.
Hint questions:
-What does drawball/1 do when its argument is 0?
-How does that affect the statements drawlines/2
and triangle/1?
---
Geoff
| |
|
|
|
|
|