/ / Triangolo degli asterischi in prolog - prolog

Triangolo degli asterischi in prolog - prolog

Devo definire la piramide prolog (N) che stampa una piramide di asterischi di altezza determinata come nell'esempio seguente.

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

true

questo è quello che ho fatto finora ... Non riesco a trovare il modo di stampare il resto delle stelle necessarie per ogni riga .. Ho anche provato a definire i predicati di supporto per gestire le parti secondarie del programma. Ma non è riuscito a trovarne uno.

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

risposte:

0 per risposta № 1

Pensa a quante stelle ogni livello ottiene in termini di N. Dì che sei in linea i, con N = 4.

  • La prima riga ottiene 3 (in realtà, N-1) spazi, una stella e altri 3 spazi.
  • La seconda linea ottiene 3 - 1 spazi, 3 stelle e altri 3 - 1 spazi.
  • ila linea diventa (N - 1) - (i - 1) spazi, 1 + 2 * (i - 1) stelle e un altro (N - 1) - (i - 1) spazi.

In questo modo:

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

Penso (ma non sono sicuro) che puoi anche rimuovere il N > 0 un po 'dal caso pyramid(0, _) sarà controllato prima


0 per risposta № 2

Qualcosa come ti dovrebbe fare:

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.