License Creative Commons Attribution Share Alike 3.0-US
Average
n/a
Rated
0
Times
5
4
3
2
1
0
Keywords
C# (7) .Net (8) Random (1)
Permissions
Viewable by Everyone
Editable by All Siafoo Users
Hide
Easily highlight source code for your blog with our Syntax Highlighter. Join Siafoo Now or Learn More

M Random Numbers Which Sum To N Atom Feed

In Brief I'm not exactly sure what it was used for but someone asked how to do this on another site and I thought it was an interesting question.... more
Performance Bound Linear
Implementation Difficulty * * * * *
 1 static void Main()
2 {
3 int count = 30;
4 int[] numbers = getNumbers(count, 155);
5 for (int index = 0; index < count; index++)
6 {
7 Console.Write(numbers[index]);
8 if ((index + 1) % 10 == 0)
9 Console.WriteLine("");
10 else if (index != count - 1)
11 Console.Write(",");
12 }
13 Console.ReadKey();
14 }
15 static int[] getNumbers(int count, int total)
16 {
17 const int LOWERBOUND = 1;
18 const int UPPERBOUND = 9;
19
20 int[] result = new int[count];
21 int currentsum = 0;
22 int low, high, calc;
23
24 if((UPPERBOUND * count) < total ||
25 (LOWERBOUND * count) > total ||
26 UPPERBOUND < LOWERBOUND)
27 throw new Exception("Not possible.");
28
29 Random rnd = new Random();
30
31 for (int index = 0; index < count; index++)
32 {
33 calc = (total - currentsum) - (UPPERBOUND * (count - 1 - index));
34 low = calc < LOWERBOUND ? LOWERBOUND : calc;
35 calc = (total - currentsum) - (LOWERBOUND * (count - 1 - index));
36 high = calc > UPPERBOUND ? UPPERBOUND : calc;
37
38 result[index] = rnd.Next(low, high + 1);
39
40 currentsum += result[index];
41 }
42
43 // The tail numbers are going to drift up or down so we should shuffle the results.
44
45 int shuffleCount = rnd.Next(count * 5, count * 10);
46 while (shuffleCount-- > 0)
47 swap(ref result[rnd.Next(0, count)], ref result[rnd.Next(0, count)]);
48
49 return result;
50 }
51 public static void swap(ref int item1, ref int item2)
52 {
53 int temp = item1;
54 item1 = item2;
55 item2 = temp;
56 }

I'm not exactly sure what it was used for but someone asked how to do this on another site and I thought it was an interesting question.