Search code examples
algorithmdelphirandomdelphi-7

Draw n random integers whose sum is equal to 100


Pseudocode example:

Random function: (1 to 5, values less than 100, sum must be equal to 100 when all random numbers are added).

Result example:

Number 1 = 35
Number 2 = 15
Number 3 = 10
Number 4 = 20
Number 5 = 20

Solution

  • Using only integer numbers and Fisher-Yates shuffle:

    program cont3;
    {$APPTYPE CONSOLE}
    {$R *.res}
    uses
      System.SysUtils;
    const
      SummandsCount = 5;
      WantedSum = 100;
    var
      i, j, t, Cnt, WhereToInsert: integer;
      JustNaturalNumbers: array[1..WantedSum] of Integer;
      DividingPoints: array[0..SummandsCount] of Integer;
    begin
      Randomize;
      Cnt := 1;
      DividingPoints[0] := 0;
      DividingPoints[SummandsCount] := 100;
      for i := 1 to WantedSum - 1 do
        JustNaturalNumbers[i] := i;
      for i := WantedSum - 1 downto WantedSum - SummandsCount + 1 do begin
        j := 1 + Random(i);
        WhereToInsert := Cnt;
        while (WhereToInsert > 1) and (JustNaturalNumbers[j] < DividingPoints[WhereToInsert-1]) do begin
          Dec(WhereToInsert);
          DividingPoints[WhereToInsert + 1] := DividingPoints[WhereToInsert]
        end;
        DividingPoints[WhereToInsert] := JustNaturalNumbers[j];
        JustNaturalNumbers[j] := JustNaturalNumbers[i];
        Inc(Cnt);
      end;
      t := 0;
      for i := 1 to SummandsCount do begin
        Writeln(DividingPoints[i] - DividingPoints[i-1]);
        t := t + (DividingPoints[i] - DividingPoints[i-1]);
      end;
        Writeln('Sum = ', t);
      Readln;
    end.
    

    Output example:

    22
    4
    7
    18
    49
    Sum = 100