绘制n个等于100的随机整数 [英] Draw n random integers whose sum is equal to 100

查看:66
本文介绍了绘制n个等于100的随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伪代码示例:

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

结果示例:

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

推荐答案

仅使用整数和Fisher-Yates随机播放:

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.

输出示例:

22
4
7
18
49
Sum = 100

这篇关于绘制n个等于100的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆