E
E
estry2020-07-04 11:21:43
C++ / C#
estry, 2020-07-04 11:21:43

How to split a number into parts?

Hello. You need to break the number into unequal parts.

I'd better show you with an example.

There is a number 2000. The number can be negative.
It must be divided into a random number of parts, for example, in the range from 5 to 10. For example, it fell out to be divided into 8 unequal parts. At the output, for example, we get:
203, 242,274,215,301,402,112,159,92

At the output we get an int array.

You can also make an error. That is, in total we get not exactly 2000, but we can get 2100.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem, 2020-07-04
@estry

I'm afraid to imagine why this might be needed, but since they ask:

int num = 2000;
int parts = 10;
Random rnd = new Random();

List<int> result = new List<int>();

for (int i = 0; i < parts - 1; i++)
{
    int tmp = rnd.Next(0, num / 2);
    if (tmp == 0) { i--; continue; } 
    result.Add(tmp);
    num -= tmp;
}

result.Add(2000 - result.Sum());

result = result.OrderBy(i => Guid.NewGuid()).ToList();

Console.WriteLine(result.Sum());

F
freeExec, 2020-07-04
@freeExec

Well, even if in total you can not get 2000 back, then it’s generally easy.
Divide 2000 by 8 to get the base number. Then we simply add or subtract some random number to this base number.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question