How to multiply every N consecutive items in an array with Pascal

1 Answer

0 votes
program ProductsNConsecutiveItemsProgram;

const
  MaxSize = 100;

type
  IntArray = array[1..MaxSize] of Integer;

var
  arr, products: IntArray;
  size, n_consecutive_items, out_size: Integer;
  i, j, prod: Integer;

begin
  { Example input list }
  size := 9;
  arr[1] := 2;
  arr[2] := 3;
  arr[3] := 4;
  arr[4] := 5;
  arr[5] := 6;
  arr[6] := 7;
  arr[7] := 8;
  arr[8] := 9;
  arr[9] := 10;

  n_consecutive_items := 3;

  { Check if we can compute products }
  if (n_consecutive_items = 0) or (size < n_consecutive_items) then
  begin
    out_size := 0;
  end
  else
  begin
    out_size := size - n_consecutive_items + 1;

    for i := 1 to out_size do
    begin
      prod := 1;

      { Multiply arr[i] * arr[i+1] * ... * arr[i+n_consecutive_items-1] }
      for j := 0 to n_consecutive_items - 1 do
        prod := prod * arr[i + j];

      products[i] := prod;

      {
        Example for n_consecutive_items = 3:
        2 * 3 * 4  = 24
        3 * 4 * 5  = 60
        4 * 5 * 6  = 120
        5 * 6 * 7  = 210
        6 * 7 * 8  = 336
        7 * 8 * 9  = 504
        8 * 9 * 10 = 720
      }
    end;
  end;

  { Print results }
  Write('[');
  for i := 1 to out_size do
  begin
    Write(products[i]);
    if i < out_size then
      Write(', ');
  end;
  WriteLn(']');
end.




(*
run:

[24, 60, 120, 210, 336, 504, 720]

*)


 



answered Feb 1 by avibootz

Related questions

...