使用c#排列货架上的物品

本文关键字:排列 使用 | 更新日期: 2023-09-27 18:04:38

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

我有一个"架子",可以放各种各样的物品。架子按位置划分,物品有一个"尺寸等级",表示它在架子上占用了多少空间。

我想为4个位置max (1,2,3,4)的架子生成所有具有3个项目(A,B,C)的填充组合,其大小类占用1个位置。(eg. AAAA, AAAB, AAAC, BBBB, BBBA, ...)

下一步,我需要生成具有2个位置的项目的排列。所以我需要用(A,B,C)生成2个位置(D,E,F)生成1个位置(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);
                }
            }                   
        }
    }
}

欢迎任何建议

使用c#排列货架上的物品

这将为您的第一个示例生成所有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将序列的每个元素投影到IEnumerable<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 }));