How to split a number into 10 different numbers?

How to split a number into 10 different numbers randomly? Such as 50390 separate it into 10 random different numbers?

1 件のコメント

Jos (10584)
Jos (10584) 2013 年 12 月 2 日
編集済み: Jos (10584) 2013 年 12 月 2 日
Do you mean that the sum of the 10 random numbers should be the original number? And should the numbers be positive, larger than zero, integers?

サインインしてコメントする。

回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2013 年 12 月 2 日
編集済み: Andrei Bobrov 2013 年 12 月 2 日

1 投票

a = 50390;
b = rand(10,1);
b = b/sum(b)*a;
out=round(b);
out(1) = out(1) - (a-sum(out));
and with using Roger Stafford's idea
a = 50390;
n = 10;
out = diff([0,sort(randperm(a-1,n-1)),a]);

1 件のコメント

Mike Akarmann
Mike Akarmann 2019 年 10 月 27 日
Great job Andrei! Simple and elegant! Thanks!

サインインしてコメントする。

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 12 月 2 日
編集済み: Azzi Abdelmalek 2013 年 12 月 2 日

0 投票

n=50390
idx=sort(randperm(n,10));
out=diff([idx n]);
out(1)=idx(1)+out(1);
sum(out)
%or in case the last number of idx is 50390
n=50390
idx=sort(randperm(n,10));
out=diff([idx n]);
out(end)=out(end)+idx(1)
sum(out)
Jos (10584)
Jos (10584) 2013 年 12 月 2 日

0 投票

Assuming all number should be positive integers larger than zero, this will give a random solution. Note that not all possible solutions are equally likely, but that might not be a problem.
S = 50390 % original number
n = 10 % partitions
f = rand(1,n)
f = f./ sum(f) % sum(f) = 1, approx.
V = round(f.*S)
V(V<1) = 1 % needs to be positive
V(1) = S - sum(V(2:end)) % deal with rounding errors etc.
isequal(sum(V),S) % check

質問済み:

2013 年 12 月 2 日

コメント済み:

2019 年 10 月 27 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by