2

我正在尝试解决排列问题,但遇到了一些问题。

我有一个可以放置各种物品的“架子”。货架按位置划分,物品有一个“尺寸等级”,表明货架本身占用了多少空间。

我想为 4 个位置的货架生成最大(1,2,3,4)所有填充组合,其中 3 个项目(A,B,C)的尺寸等级占 1 个位置。(eg. AAAA, AAAB, AAAC, BBBB, BBBA, ...).

下一步,我需要使用占据 2 个位置的项目生成排列。所以我需要生成 2 个位置(A,B,C)和 1 个位置(D,E,F) (eg. AAD, AAE, ABD, ...)

我试过在这里使用这个库,但我的解决方案远非很好(而且它不能解决第二个例子)

using System;
using System.Linq;
using System.Collections.Generic;
using Facet.Combinatorics;

namespace iCombine
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            char[] inputSet = "ABCABCABCABC".ToCharArray ();
            IList<string> uniques = new List<string>(); 

            var combinations = new Combinations<char> (inputSet, 4, GenerateOption.WithoutRepetition);
            foreach (var combination in combinations) {
                var permutations = new Permutations<char> (combination, GenerateOption.WithoutRepetition);
                foreach (IList<char> permutation in permutations) {     
                    string token = new string (permutation.ToArray(), 0, 4);
                    if (!uniques.Contains(token))
                        uniques.Add(token);
                }
            }                   
        }
    }
}

欢迎任何建议:)

4

1 回答 1

3

这将为您的第一个示例生成所有 81 个排列:

var items = new List<char>{'A', 'B', 'C'};

var perms = from a in items
            from b in items
            from c in items
            from d in items
            select new string(new char[]{a, b, c, d});

例如

AAAA 
AAAB 
AAAC 
AABA 
AABB 
...

这是您的第二个示例的 27 个排列:

var items = new List<char>{'A', 'B', 'C'};
var items2 = new List<char> {'D', 'E', 'F'};

var perms = from a in items
            from b in items
            from c in items2
            select new string(new char[]{a, b, c});

等效的方法语法使用Enumerable.SelectMany,它将序列的每个元素投影到 anIEnumerable<T>并将结果序列展平为一个序列。

所以上面的查询可以写成:

var items = new List<char> { 'A', 'B', 'C' };
var items2 = new List<char> { 'D', 'E', 'F' };

var perms = items.SelectMany(a => items, (a, b) => new { a, b })
            .SelectMany(t => items2, (t, c) => new string(new[] { t.a, t.b, c }));
于 2013-03-18T22:44:30.077 回答