Trójkąty z gwiazdek rekurencyjnie.

Trójkąty z gwiazdek rekurencyjnie.
MO
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 74
0

Możecie mnie naprowadzić jakoś ja rekurencyjnie zrobić z gwiazdek poniższy wzór?
Przykład dla n=5:

Kopiuj
*****
****
***
**
*
Kopiuj
 
program zs;

{$APPTYPE CONSOLE}

uses
  SysUtils;
function gwiazdki(n:integer):integer;
  var
  i:integer;
  begin
    if (n<>1) then result:=gwiazdki(n-1);
    write('*');
  end;
var
  n:integer;
begin
  writeln('Podaj N:');
  readln(n);
  gwiazdki(n);
  readln;
end.
_13th_Dragon
  • Rejestracja: dni
  • Ostatnio: dni
1
Kopiuj
procedure gwiazdki(n:integer);
var i:integer;
begin
    if n>0 then
    begin
      for i=1 to n Write('*');
      WriteLn;
      gwiazdki(n-1);
    end;
end;
MO
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 74
0

Zapomniałem dodać jeszcze, że w programie nie można użyć pętli

_13th_Dragon
  • Rejestracja: dni
  • Ostatnio: dni
0

Więc potrzebujesz dodać jeszcze jeden parametr.

flowCRANE
  • Rejestracja: dni
  • Ostatnio: dni
  • Lokalizacja: Tuchów
  • Postów: 12317
2
Kopiuj
procedure StarsLine(ALength: Integer);
begin
  if ALength > 0 then
  begin
    WriteLn(StringOfChar('*', ALength));
    StarsLine(ALength - 1);
  end;
end;

@morodis - nie ma pętli; A jeśli jej poszukać, to StringOfChar także jej nie posiada, dopiero użyty w niej FillChar gdzieś tam na najniższym poziomie ją posiada;

Przykład bez pętli i funkcji je maskujących:

Kopiuj
procedure StarsLine(ALength, AStarIdx: Integer);
begin
  if ALength = 0 then Exit();

  if AStarIdx > ALength then
  begin
    WriteLn();
    StarsLine(ALength - 1, 1);
  end
  else
  begin
    Write('*');
    StarsLine(ALength, AStarIdx + 1);
  end;
end;

Gdyby posłużyć się funkcją IfThen z modułu StrUtils, kod skróci się do poniższej postaci:

Kopiuj
uses
  StrUtils;

  procedure StarsLine(ALength, AStarIdx: Integer);
  begin
    if ALength = 0 then Exit();

    Write(IfThen(AStarIdx > ALength, #10, '*'));

    if AStarIdx > ALength then
      StarsLine(ALength - 1, 1)
    else
      StarsLine(ALength, AStarIdx + 1);
  end;

Można też użyć stałej tablicy znaków, indeksowanej typem Boolean, jednak to redundantne; Szkoda, że w Delphi czy Free Pascalu nie wymyślili jeszcze operatora trójargumentowego...

Dorzućmy jeszcze jeden parametr i IfThen z modułu Math, a wyjdzie jeszcze krócej:

Kopiuj
uses
  StrUtils, Math;

  procedure StarsLine(ALength, AStarIdx: Integer; AEoL: Boolean);
  begin
    if ALength = 0 then Exit();

    Write(IfThen(AEoL, #10, '*'));
    StarsLine(IfThen(AEoL, ALength - 1, ALength), IfThen(AEoL, 1, AStarIdx + 1), AStarIdx = ALength);
  end;

Nie no żartuję - wyszedł potwór.

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.