【问题标题】:Getting all permutations for weightings according to an interval根据间隔获取权重的所有排列
【发布时间】:2011-07-26 21:12:31
【问题描述】:

如果我有给定数量的“系统”

var nbSystems = 2;

还有一些“步骤”

var nbSteps = 3;

如何生成以下所有排列:

{0.00, 0.00}
{0.33, 0.00}
{0.67, 0.00}
{1.00, 0.00}
{0.00, 0.33}
{0.33, 0.33}
{0.67, 0.33}
{1.00, 0.33}
{0.00, 0.66}
{0.33, 0.66}
{0.67, 0.66}
{1.00, 0.66}
{0.00, 1.00}
{0.33, 1.00}
{0.67, 1.00}
{1.00, 1.00}

我需要每个系统的权重在 0 到 1 之间,并且我想找到所有排列。

您会看到用于系统权重的间隔是根据 nbSteps (interval = 1 / nbSteps) 计算得出的。

我想要一个函数,它接受输入 nbSystems 和 nbSteps(或更好?),并输出某种具有所有排列的多维数组...

【问题讨论】:

  • nbSystems 是数组的维数?

标签: c# arrays permutation combinations combinatorics


【解决方案1】:

应该这样做:

static void Main(string[] args)
{
    var nbSystems = 2;
    var nbSteps = 3;

    var steps = GetSteps(0, 1, nbSteps).Select(n => Math.Round(n, 2)).ToArray();
    foreach (var seq in GetCombinations(steps, nbSystems))
        Console.WriteLine(string.Join(", ", seq));
}

private static IEnumerable<decimal> GetSteps(decimal min, decimal max, int count)
{
    var increment = (max - min) / count;
    return Enumerable.Range(0, count + 1).Select(n => min + increment * n);
}

private static IEnumerable<IEnumerable<T>> GetCombinations<T>(
    ICollection<T> choices, int length)
{
    if (length == 0)
    {
        yield return new T[0];
        yield break;
    }

    foreach (var choice in choices)
        foreach (var suffix in GetCombinations(choices, length - 1))
            yield return Enumerable.Concat(new[] { choice }, suffix);
}

如果您关心组合的顺序,请根据需要进行调整。

编辑:糟糕,修正了一个错字 - 我在我的类型签名中转换了“max”和“min”。

【讨论】:

  • 看起来不错,太棒了!我会对其进行更多测试,它应该很快就会成为公认的答案。再次感谢:)
  • 这里不输出数组,只输出控制台行。
【解决方案2】:

试试

double nbSteps = 3.0;

IEnumerable<double> SystemA = Enumerable.Range (0, (int)nbSteps).Select (x => x / nbSteps); 
IEnumerable<double> SystemB = Enumerable.Range (0, (int)nbSteps).Select (x => x / nbSteps); 

var Result = from a in SystemA from b in SystemB select new { a, b };

【讨论】:

  • +1 学习,看起来很有趣!是否可以使其更通用以接受任意数量的系统? :)
  • 你从哪里得到 Range 的 int,double 方法签名?我可能只是错过了它,但我似乎找不到它。
  • 查看 msdn.microsoft.com/en-us/library/… 了解 int 版本...稍微更正了我的代码...谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
相关资源
最近更新 更多