2015-01-13 116 views
0

我必須定義打印出給定高度星號金字塔的序言金字塔(N),如下例所示。星號在序言中的三角形

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

true 

這是我迄今所做的...... 我找不到打印出所需的各線明星的休息方式.. 我也試圖定義支持謂詞來處理子部分的程序,但沒有找到一個。

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

類似的問題在這裏:怎樣繪製星三角Prolog的使用遞歸(http://stackoverflow.com/questions/20009868/how-can-i使用-draw星級三角形遞歸功能於序言) – lurker

回答

0

想想每個級別有多少星級獲得N。說你是在線路i,與N = 4

  • 第一行得3(實際上,N-1)空間,明星,另有3位。
  • 第二行獲得3 - 1個空格,3個星號和另外3 - 1個空格。
  • i th line獲取(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, _)將首先檢查。

0

事情是應該做的你:

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.