我有以下场景:
- 从一定范围内生成
n
个随机数 - 对所有数字求和
- 检查
sum == x
(x是用户设置的数字) - if
sum != x
then keep running the loop - 如果
sum == x
,则显示总和为x
的随机数列表
根据这个逻辑,我是可以这样做的,但是需要很长时间才能达到结果,有没有更好的/方法来解决这个问题?
static void Main(string[] args)
{
Console.WriteLine("starting...");
List<int> checkList = generate(5);
while(!checkSum(checkList, 100))
{
checkList = generate(5)
}
Console.WriteLine("done!");
}
private static bool checkSum(List<int> n, int sum)
{
if(n.Sum() == sum)
{
return true;
}
else
{
return false;
}
}
public static List<int> generate(int n)
{
Random rng = new Random();
List<int> list = new List<int>();
for (int i = 0; i < 5; i++)
{
//int ran = some random number
list.Add(ran);
}
return list;
}
编辑
我的场景是获取总和为 100 的随机整数的 n
组合。组合的数量取自用户的输入。因此程序将给出 n
种可能的组合,总和为 100。
可能的组合:
- 25+37+9+20+9 = 100
- 46+21+13+8+12 = 100
最佳答案
如果您有一个固定的总和和固定数量的元素,请将问题视为分区。例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PartitionAndAllocateTEst
{
class Program
{
static void Main(string[] args)
{
var rand = new Random();
int desiredTotal = 100;
int partitions = 5;
for (int i = 0; i < 10; i++)
{
List<int> result = GetRandomCollection(rand, desiredTotal, partitions);
Console.WriteLine(string.Join(", ", result.Select(r => r.ToString()).ToArray()));
}
}
private static List<int> GetRandomCollection(Random rand, int desiredTotal, int partitions)
{
// calculate the weights
var weights = new List<double>();
for (int i = 0; i < partitions; i++)
{
weights.Add(rand.NextDouble());
}
var totalWeight = weights.Sum();
// allocate the integer total by weight
// http://softwareengineering.stackexchange.com/questions/340393/allocating-an-integer-sum-proportionally-to-a-set-of-reals/340394#340394
var result = new List<int>();
double allocatedWeight = 0;
int allocatedCount = 0;
foreach (var weight in weights)
{
var newAllocatedWeight = allocatedWeight + weight;
var newAllocatedCount = (int)(desiredTotal * (newAllocatedWeight / totalWeight));
var thisAllocatedCount = newAllocatedCount - allocatedCount;
allocatedCount = newAllocatedCount;
allocatedWeight = newAllocatedWeight;
result.Add(thisAllocatedCount);
}
return result;
}
}
}
示例输出:
30, 6, 19, 15, 30
36, 8, 22, 10, 24
2, 25, 32, 21, 20
22, 7, 30, 12, 29
36, 21, 22, 0, 21
24, 24, 2, 29, 21
18, 13, 10, 39, 20
11, 19, 20, 27, 23
24, 19, 7, 25, 25
24, 14, 27, 18, 17
关于C# 随机算法直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42563732/