序言中的星号三角形 [英] Asterisks Triangle in prolog

查看:38
本文介绍了序言中的星号三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须定义 prolog pyramid(N),它打印出给定高度的星号金字塔,如下例所示.

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

推荐答案

你应该做的事情:

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.

这篇关于序言中的星号三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆