如何得到一组duplicatable元素的所有唯一正长的组合? [英] How to get all the unique n-long combinations of a set of duplicatable elements?

查看:91
本文介绍了如何得到一组duplicatable元素的所有唯一正长的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有很多的解决方案提供一个集合中的元素组合在所有可能的订单,但它们都使用每一个元素只有一次在每一个结果,而我需要他们被视为可重复使用的。

I have found many solutions giving a collection elements combined in all possible orders but they all use every element just once in every result while I need them to be treated as reusable.

例如,如果输入元素是{一,B,C}和数量为2的输出是属于{一,一个},{一,b的},{一,C},{B,一个},{B,B},{B,C},{C,一个 },{C,B},{一,C}

For example if input elements are {"a", "b", "c"} and the number is 2 the output is to be {"a", "a"}, {"a", "b"}, {"a", "c"}, {"b", "a"}, {"b", "b"}, {"b", "c"}, {"c", "a"}, {"c", "b"}, {"a", "c"}.

推荐答案

埃里克利珀有presented从任何数字序列的这是他博客关于这里

Eric Lippert has presented a general-purpose method of generating a cartesian product from any number of sequences which he blogs about here.

他写道,看起来像这样一个扩展方法:

He wrote an extension method that looks like this:

public static class Combinations
{
    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
    {
        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
        return sequences.Aggregate(
            emptyProduct,
            (accumulator, sequence) =>
            from accseq in accumulator
            from item in sequence
            select accseq.Concat<T>(new[] { item }));
    }
}

鉴于扩展方法,解决了原来的问题可以这样做:

Given that extension method, the solution to the original problem can be done like this:

var items = new[] { "a", "b", "c" };

int numInEachSelection = 2;

var combs = Enumerable.Repeat(items, numInEachSelection).CartesianProduct();

foreach (var comb in combs)
    Console.WriteLine(string.Join(", ", comb));

注意梳子的IEnumerable&LT; IEnumerable的&LT;字符串&GT;&GT; - 这是每一个可枚举序列这是一个顺序重新presenting一种组合

Note that combs is an IEnumerable<IEnumerable<string>> - it is a sequence of enumerables each of which is a sequence representing one combination.

如果你并不需要一个通用的方法,这样,你很高兴有一个单独的对象中的每个组合称为属性项目1 项目2 的两个组合的项目,最简单的方法是这样的:

If you don't need a general-purpose method like that and you are happy to have each combination in a separate object with properties called Item1 and Item2 for the two combined items, the easiest way is this:

var items = new[] { "a", "b", "c" };

var combs = from Item1 in items from Item2 in items select new {Item1, Item2};

foreach (var comb in combs)
    Console.WriteLine(comb);

这篇关于如何得到一组duplicatable元素的所有唯一正长的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆