问题描述
如何生成30随机数字1-9之间,所有加起来200(或任意N),在C#?
How do I generate 30 random numbers between 1-9, that all add up to 200 (or some arbitrary N), in C#?
我想产生一个数字字符串,可以加在一起为N。
I'm trying to generate a string of digits that can add together to be N.
推荐答案
我不知道什么是统计上的这一点,但这里的问题是,你不希望随机选择一个数字,使得它不可能总之n,其中的条目,或用过冲或下冲的M号。下面是我会怎么做:
I'm not sure what the statistics are on this but, the issue here is that you don't want to randomly select a number that makes it impossible to sum N with M number of entries either by overshooting or undershooting. Here's how I would do it:
static void Main()
{
int count = 30;
int[] numbers = getNumbers(count, 155);
for (int index = 0; index < count; index++)
{
Console.Write(numbers[index]);
if ((index + 1) % 10 == 0)
Console.WriteLine("");
else if (index != count - 1)
Console.Write(",");
}
Console.ReadKey();
}
static int[] getNumbers(int count, int total)
{
const int LOWERBOUND = 1;
const int UPPERBOUND = 9;
int[] result = new int[count];
int currentsum = 0;
int low, high, calc;
if((UPPERBOUND * count) < total ||
(LOWERBOUND * count) > total ||
UPPERBOUND < LOWERBOUND)
throw new Exception("Not possible.");
Random rnd = new Random();
for (int index = 0; index < count; index++)
{
calc = (total - currentsum) - (UPPERBOUND * (count - 1 - index));
low = calc < LOWERBOUND ? LOWERBOUND : calc;
calc = (total - currentsum) - (LOWERBOUND * (count - 1 - index));
high = calc > UPPERBOUND ? UPPERBOUND : calc;
result[index] = rnd.Next(low, high + 1);
currentsum += result[index];
}
// The tail numbers will tend to drift higher or lower so we should shuffle to compensate somewhat.
int shuffleCount = rnd.Next(count * 5, count * 10);
while (shuffleCount-- > 0)
swap(ref result[rnd.Next(0, count)], ref result[rnd.Next(0, count)]);
return result;
}
public static void swap(ref int item1, ref int item2)
{
int temp = item1;
item1 = item2;
item2 = temp;
}
我没有很多时间来测试这个如此道歉,如果有一个在我的逻辑缺陷的地方。
I didn't have a lot of time to test this so apologies if there's a flaw in my logic somewhere.
编辑:
我做了一些测试,一切似乎固体。如果你想要一个漂亮的pretty的小号$ P $垫,它看起来像你想沿着东西线总=计数*((UPPER + LOWER)/ 2)
。虽然我相当肯定,如上
和下
之间的差异增加了更灵活的这成为
I did some testing and everything seems solid. If you want a nice pretty spread it looks like you want something along the lines of Total = Count * ((UPPER + LOWER) / 2)
. Although I'm fairly certain that as the difference between UPPER
and LOWER
increases the more flexible this becomes.
这篇关于产生一系列的随机数字,加起来就是N的C#的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!