使用空格在prolog中编写递归星号函数

时间:2017-12-19 15:51:53

标签: prolog

我要在prolog中编写一个谓词,它接受一个整数X并输出一个镜像的星号模式:

******
**  **
*    *
*    *
**  **
******

2 个答案:

答案 0 :(得分:0)

此程序打印所需的模式(我用非核心替换了空格):

printStar(0).
printStar(N):-
    write('*'),
    N1 is N-1,
    printStar(N1).

printSpaces(0).
printSpaces(N):-
    write('_'),
    N1 is N-1,
    printSpaces(N1).

printUpperPattern(0,_).
printUpperPattern(N,R):-
    N > 0,
    Spaces is 2*R - 2,
    printStar(N),
    printSpaces(Spaces),
    printStar(N),
    nl,
    N1 is N-1,
    R1 is R+1,
    printUpperPattern(N1,R1).

printLowerPattern(0,_).
printLowerPattern(N,R):-
    N > 0,
    Spaces is 2*N - 2,
    printStar(R),
    printSpaces(Spaces),
    printStar(R),
    nl,
    N1 is N-1,
    R1 is R+1,
    printLowerPattern(N1,R1).

pattern(N):-
    printUpperPattern(N,1),
    printLowerPattern(N,1).

答案 1 :(得分:0)

你可以这样做:

rectangle(Len) :-
    Max is Len/2 - 1,
    forall(between(0,Max,I), write_line(Max, I)),
    forall(between(0,Max,I), (J is Max-I, write_line(Max, J))).

write_line(Max, N) :-
    Stars is Max+1 - N,
    Spaces is 2 * N,
    forall(between(1,Stars, _), write('*')),
    forall(between(1,Spaces, _), write(' ')),
    forall(between(1,Stars, _), write('*')),
    nl.

例如:

?- rectangle(6).
******
**  **
*    *
*    *
**  **
******
true.

?- rectangle(8).
********
***  ***
**    **
*      *
*      *
**    **
***  ***
********
true.

?- rectangle(10).
**********
****  ****
***    ***
**      **
*        *
*        *
**      **
***    ***
****  ****
**********
true.