Solved

# C# dividing a number into 24 random pieces/shares

Posted on 2013-05-12
491 Views
Hey guys,

I'm trying to figure out the easiest way to divide a number into 24 parts, but completely random.

For example, if the number is 15,500 how would I be able to divide it up randomly into 24 parts like this:

1. 253
2. 442
3. 101
4. 788
5. 2,232
etc....

The sum of these 24 random pieces should = 15,500.

Any thoughts?
0
Question by:mcainc
• 2
• 2

LVL 42

Expert Comment

should they all be different?
0

Author Comment

yeah, all 24 pieces should be different random numbers that all add up to the desired larger number
0

LVL 42

Accepted Solution

sedgwick earned 500 total points
here it is:
``````        static Random rand = new Random();
public static IEnumerable<int> Split(Int32 val, int parts)
{
int left = val;
for (int i = 0; i < parts - 1; i++)
{
var curr = rand.Next(1, left / parts);
yield return curr;
left -= curr;
}
yield return left;
}

static void Main(string[] args)
{
Int32 val = 15500;
var res = Split(val, 24);
int sum = 0;
foreach (var item in res)
{
Console.WriteLine(item);
sum += item;
}
var match = (sum == val);

}
``````
0

Author Closing Comment

nice!!! thanks
0

## Featured Post

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.