【问题标题】:Asterisks Triangle in prolog序言中的星号三角形
【发布时间】:2015-01-14 02:50:54
【问题描述】:

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

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

true

这是我到目前为止所做的...... 我找不到打印出每行所需的其余星星的方法.. 我还尝试定义支持谓词来处理程序的子部分。但没有找到。

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

【问题讨论】:

标签: prolog


【解决方案1】:

根据N,想想每个关卡有多少颗星。假设您在i 行,N = 4。

  • 第一行有 3 个(实际上是 N-1)空格、一个星号和另外 3 个空格。
  • 第二行获得 3 - 1 个空格、3 颗星和另外 3 - 1 个空格。
  • ith 行得到 (N - 1) - (i - 1) 空格、1 + 2 * (i - 1) 星号和另一个 (N - 1) - (i - 1) 空格。

这样给出:

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

我认为(但不确定)您也可以删除N > 0 位,因为将首先检查pyramid(0, _) 的情况。

【讨论】:

    【解决方案2】:

    你应该这样做:

    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      相关资源
      最近更新 更多