How to build a pyramid from the numbers 3, 7, 5, 2, 4, 8, 6, 9, 0, 3 in Pascal

1 Answer

0 votes
program PyramidDemo;

{$mode objfpc}{$H+}


type
  TIntArray = array of Integer;
  TPyramid  = array of TIntArray;

// ------------------------------------------------------------
// Build a pyramid from a flat list of numbers
// ------------------------------------------------------------
function buildPyramid(const nums: TIntArray): TPyramid;
var
  pyramid: TPyramid;
  index, rowSize, r, i: Integer;
begin
  index := 0;
  rowSize := 1;
  SetLength(pyramid, 0);

  while index + rowSize <= Length(nums) do
  begin
    SetLength(pyramid, Length(pyramid) + 1);
    r := High(pyramid);
    SetLength(pyramid[r], rowSize);

    for i := 0 to rowSize - 1 do
    begin
      pyramid[r][i] := nums[index];
      Inc(index);
    end;

    Inc(rowSize);
  end;

  Result := pyramid;
end;

// ------------------------------------------------------------
// Print the pyramid centered
// ------------------------------------------------------------
procedure printPyramid(const pyramid: TPyramid);
var
  height, r, c, spaces: Integer;
begin
  height := Length(pyramid);

  for r := 0 to height - 1 do
  begin
    // Print leading spaces
    spaces := (height - r - 1) * 2;
    Write(StringOfChar(' ', spaces));

    // Print row values
    for c := 0 to High(pyramid[r]) do
      Write(pyramid[r][c], '   ');

    WriteLn;
  end;
end;

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
var
  numbers: TIntArray;
  pyramid: TPyramid;
begin
  numbers := TIntArray.Create(3, 7, 5, 2, 4, 8, 6, 9, 0, 3);

  pyramid := buildPyramid(numbers);

  WriteLn('Pyramid:');
  printPyramid(pyramid);
end.



(*
run:

Pyramid:
      3   
    7   5   
  2   4   8   
6   9   0   3   

*)

 



answered 2 hours ago by avibootz
...