清单的独特组合 [英] Unique combinations of list

查看:67
本文介绍了清单的独特组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此绝对空白。那是其中的一天。但是我一直在寻找一种解决方案,以获取特定长度的项目列表的唯一组合。例如,给定列表[a,b,c]和长度为2,它将返回[a,b] [a,c] [b,c],但不返回[b,a] [c,a] [c ,b]

Absolute mind blank on this. It's been one of those days. But I have been looking for a solution for getting unique combinations of a list of items of a certain length. e.g., given a list [a, b, c] and a length of 2, it will return [a,b] [a,c] [b,c] but not [b,a] [c,a] [c,b]

为此,我发现了很多代码,但似乎都不合适。以下代码似乎最合适,并且我一直在尝试根据需要对其进行更改:

For this I found numerous pieces of code, but none which seems to fit. The following code seemed best fit and I've been trying to alter it for my needs:

// Returns an enumeration of enumerators, one for each permutation
// of the input.
public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> list, int count)
{
    if (count == 0)
    {
        yield return new T[0];
    }
    else
    {
        int startingElementIndex = 0;
        foreach (T startingElement in list)
        {
            IEnumerable<T> remainingItems = AllExcept(list, startingElementIndex);

            foreach (IEnumerable<T> permutationOfRemainder in Permute(remainingItems, count - 1))
            {
                yield return Concat<T>(
                    new T[] { startingElement },
                    permutationOfRemainder);
            }
            startingElementIndex += 1;
        }
    }
}

// Enumerates over contents of both lists.
public static IEnumerable<T> Concat<T>(IEnumerable<T> a, IEnumerable<T> b)
{
    foreach (T item in a) { yield return item; }
    foreach (T item in b) { yield return item; }
}

// Enumerates over all items in the input, skipping over the item
// with the specified offset.
public static IEnumerable<T> AllExcept<T>(IEnumerable<T> input, int indexToSkip)
{
    int index = 0;
    foreach (T item in input)
    {
        if (index != indexToSkip) yield return item;
        index += 1;
    }
}

这确实应该执行,但是返回所有排列,无论它们是唯一的。我试图弄清楚该代码的哪一部分(如果有的话)进行更改以获取唯一值。还是实现此功能的更好方法?

This does what it is supposed to do, but it returns ALL permutations, regardless of them being unique. I've tried to get my head around which piece, if any, of this code to change to get the unique values. Or is the a better way to implement this functionality?

推荐答案

实现中的其余项列表包含当前开始项之外的所有项

The remaining items list in the implementation contains all items except the current starting item.

获取起始项之后的项目:

Get the items that are after the starting item instead:

IEnumerable<T> remainingItems = list.Skip(startingElementIndex + 1);

这篇关于清单的独特组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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