C# 随机算法直到满足条件

标签 c# algorithm random

我有以下场景:

  1. 从一定范围内生成n个随机数
  2. 对所有数字求和
  3. 检查sum == x(x是用户设置的数字)
  4. if sum != x then keep running the loop
  5. 如果 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/

相关文章:

c# - 使用 iText 从 pdf 中提取字体名称、大小、样式

c# - Python 的 xml.etree getiterator 相当于 C#

java - Java中的随机16位数字函数

python - 如何使用 Python 从指定目录(随机)打开一系列文件(PNG)?

r - R 中的 Shuffle 向量,但相同元素应该有最小距离

c# - Redis 是本地缓存的可行解决方案吗?

c# - 自托管 ASP.NET Core 2.0 : TagHelper doesnt work

algorithm - 查找 xor 为 0 的子数组

java - 如果包含在特定的结尾列表中,则删除单词结尾

c - Kadane 算法中的查询