How do I generate 8
random numbers from 1
to 100
The sum of 8
numbers is 200
Not Without repeating the same numbers in each group Showing all possible outcomes.
It depends on what random means here. You can, for instance, put a problem like this:
There is a stick of length
200
We should put8 - 1 = 7
random marks on it to cut stick into8
pieces and return the lengths of these pieces.
Let's draw a pictute:
[----------------------------------------------------------]
^ ^ ^ ^ ^ ^ ^ ^ ^
0 33 83 135 138 157 177 186 200 <- points
33 50 52 3 19 20 9 14 <- lengths
Code:
Random random = new Random();
...
int length = 200;
int count = 8;
int prior = 0;
int[] values = Enumerable
.Range(0, count - 1)
.Select(_ => random.Next(0, length + 1))
.OrderBy(item => item)
.Append(length)
.Select(item => {
int savedPrior = prior;
prior = item;
return item - savedPrior; })
.ToArray();
If you want all values
being distinct you can try repeating the procedure when they are not:
int[] values;
int length = 200;
int count = 8;
do {
int prior = 0;
values = Enumerable
.Range(0, count - 1)
.Select(_ => random.Next(0, length + 1))
.OrderBy(item => item)
.Append(length)
.Select(item => {
int savedPrior = prior;
prior = item;
return item - savedPrior; })
.Distinct()
.ToArray();
}
while (values.Length != count);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.