Asterisks Triangle in prolog

2019-09-08 09:20发布

I have to define the prolog pyramid(N) that prints out a pyramid of asterisks of given height as in the following example.

pyramid(4).  
   * 
  *** 
 ***** 
******* 

true

this is what i have done so far... I can't find the way to print out the rest of stars needed for each lines.. I also tried to define support predicates to handle subparts of the program.but failed to find one.

pyramid(0) :-
   nl.
pyramid(N) :-
   N > 0,
   N1 is N - 1,
   foreach(between(1,N1,_), write(' ')),
   write('*'), nl,
   pyramid(N1).

标签: prolog
2条回答
该账号已被封号
2楼-- · 2019-09-08 09:38

Think of how many stars each level gets in terms of N. Say you are at line i, with N = 4.

  • First line gets 3 (actually, N-1) spaces, a star, and another 3 spaces.
  • Second line gets 3 - 1 spaces, 3 stars, and another 3 - 1 spaces.
  • ith line gets (N - 1) - (i - 1) spaces, 1 + 2 * (i - 1) stars, and another (N - 1) - (i - 1) spaces.

So that gives:

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).

I think (but not sure) you can also remove the N > 0 bit since the case pyramid(0, _) will be checked first.

查看更多
何必那么认真
3楼-- · 2019-09-08 09:48

Something like should do you:

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.
查看更多
登录 后发表回答