我有一个与已回答的问题类似但不相同的问题 这里。

我想要一个函数生成所有的 k-n 个元素列表中元素的组合。请注意,我正在寻找组合,而不是排列,并且我们需要一个针对不同情况的解决方案 k (即,对循环进行硬编码是不允许的)。

我正在寻找一种解决方案,a)优雅,b)可以用 VB10/.Net 4.0 编码。

这意味着 a) 需要 LINQ 的解决方案是可以的,b) 使用 C#“yield”命令的解决方案则不行。

组合的顺序并不重要(即字典顺序、格雷码、what-have-you),如果两者发生冲突,则优雅优先于性能。

(OCaml 和 C# 解决方案 这里 如果可以用 VB10 进行编码就完美了。)

有帮助吗?

解决方案

代码在C#产生组合的列表作为ķ元素的数组:

public static class ListExtensions
{
    public static IEnumerable<T[]> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        List<T[]> result = new List<T[]>();

        if (k == 0)
        {
            // single combination: empty set
            result.Add(new T[0]);
        }
        else
        {
            int current = 1;
            foreach (T element in elements)
            {
                // combine each element with (k - 1)-combinations of subsequent elements
                result.AddRange(elements
                    .Skip(current++)
                    .Combinations(k - 1)
                    .Select(combination => (new T[] { element }).Concat(combination).ToArray())
                    );
            }
        }

        return result;
    }
}

这里使用集合初始化语法是在VB 2010(可用源)。

其他提示

我试图创建可在VB完成此任务可枚举。这是结果:

Public Class CombinationEnumerable(Of T)
Implements IEnumerable(Of List(Of T))

Private m_Enumerator As CombinationEnumerator

Public Sub New(ByVal values As List(Of T), ByVal length As Integer)
    m_Enumerator = New CombinationEnumerator(values, length)
End Sub

Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of List(Of T)) Implements System.Collections.Generic.IEnumerable(Of List(Of T)).GetEnumerator
    Return m_Enumerator
End Function

Private Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
    Return m_Enumerator
End Function

Private Class CombinationEnumerator
    Implements IEnumerator(Of List(Of T))

    Private ReadOnly m_List As List(Of T)
    Private ReadOnly m_Length As Integer

    ''//The positions that form the current combination
    Private m_Positions As List(Of Integer)

    ''//The index in m_Positions that we are currently moving
    Private m_CurrentIndex As Integer

    Private m_Finished As Boolean


    Public Sub New(ByVal list As List(Of T), ByVal length As Integer)
        m_List = New List(Of T)(list)
        m_Length = length
    End Sub

    Public ReadOnly Property Current() As List(Of T) Implements System.Collections.Generic.IEnumerator(Of List(Of T)).Current
        Get
            If m_Finished Then
                Return Nothing
            End If
            Dim combination As New List(Of T)
            For Each position In m_Positions
                combination.Add(m_List(position))
            Next
            Return combination
        End Get
    End Property

    Private ReadOnly Property Current1() As Object Implements System.Collections.IEnumerator.Current
        Get
            Return Me.Current
        End Get
    End Property

    Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext

        If m_Positions Is Nothing Then
            Reset()
            Return True
        End If

        While m_CurrentIndex > -1 AndAlso (Not IsFree(m_Positions(m_CurrentIndex) + 1)) _
            ''//Decrement index of the position we're moving
            m_CurrentIndex -= 1
        End While

        If m_CurrentIndex = -1 Then
            ''//We have finished
            m_Finished = True
            Return False
        End If
        ''//Increment the position of the last index that we can move
        m_Positions(m_CurrentIndex) += 1
        ''//Add next positions just after it
        Dim newPosition As Integer = m_Positions(m_CurrentIndex) + 1
        For i As Integer = m_CurrentIndex + 1 To m_Positions.Count - 1
            m_Positions(i) = newPosition
            newPosition += 1
        Next
        m_CurrentIndex = m_Positions.Count - 1
        Return True
    End Function

    Public Sub Reset() Implements System.Collections.IEnumerator.Reset
        m_Finished = False
        m_Positions = New List(Of Integer)
        For i As Integer = 0 To m_Length - 1
            m_Positions.Add(i)
        Next
        m_CurrentIndex = m_Length - 1
    End Sub

    Private Function IsFree(ByVal position As Integer) As Boolean
        If position < 0 OrElse position >= m_List.Count Then
            Return False
        End If
        Return Not m_Positions.Contains(position)
    End Function

    ''//Add IDisposable support here


End Class

End Class

...你可以使用我的代码是这样的:

Dim list As New List(Of Integer)(...)
Dim iterator As New CombinationEnumerable(Of Integer)(list, 3)
    For Each combination In iterator
        Console.WriteLine(String.Join(", ", combination.Select(Function(el) el.ToString).ToArray))
    Next

我的代码给指定长度的组合(3在我的例子),虽然,我才意识到,你希望有任何长度(我认为)的组合,但它是一个良好的开端。

我不清楚您希望 VB 代码以什么形式返回它生成的组合,但为了简单起见,我们假设一个列表列表。VB 确实允许递归,并且递归解决方案是最简单的。通过简单地遵守输入列表的顺序,可以轻松地进行组合而不是排列。

因此,N 个项目长的列表 L 中 K 个项目的组合为:

  1. 无,如果 K > N
  2. 整个列表 L,如果 K == N
  3. 如果 K < N,则两束的并集:包含L的第一项和其他N-1项中K-1项的任意组合;再加上其他 N-1 项的 K 组合。

在伪代码中(例如使用 .size 给出列表的长度,[] 作为空列表,.append 将项目添加到列表中,.head 获取列表的第一项,.tail 获取“除L) 的第一项:

function combinations(K, L):
  if K > L.size: return []
  else if K == L.size: 
    result = []
    result.append L
    return result
  else:
    result = []
    for each sublist in combinations(K-1, L.tail):
      subresult = []
      subresult.append L.head
      for each item in sublist:
        subresult.append item
      result.append subresult
    for each sublist in combinations(K, L.tail):
      result.append sublist
    return result

如果您采用更灵活的列表操作语法,则可以使该伪代码更加简洁。例如,在 Python(“可执行伪代码”)中使用“切片”和“列表理解”语法:

def combinations(K, L):
  if K > len(L): return []
  elif K == len(L): return [L]
  else: return [L[:1] + s for s in combinations(K-1, L[1:])
               ] + combinations(K, L[1:])

无论您需要通过重复的 .append 详细地构造列表,还是可以通过列表理解符号简洁地构造它们,都是一个语法细节(就像选择头和尾与列表切片符号来获取列表的第一项与其余项一样) ):伪代码旨在表达完全相同的想法(这也是前面编号列表中用英语表达的相同想法)。您可以用任何能够递归的语言来实现这个想法(当然,还有一些最小的列表操作!-)。

我捻,第1移送排序的列表,由长度 - 然后通过阿尔法

Imports System.Collections.Generic

Public Class LettersList

    Public Function GetList(ByVal aString As String) As List(Of String)
        Dim returnList As New List(Of String)

        ' Start the recursive method
        GetListofLetters(aString, returnList)

        ' Sort the list, first by length, second by alpha
        returnList.Sort(New ListSorter)

        Return returnList
    End Function

    Private Sub GetListofLetters(ByVal aString As String, ByVal aList As List(Of String))
        ' Alphabetize the word, to make letter key
        Dim tempString As String = Alphabetize(aString)

        ' If the key isn't blank and the list doesn't already have the key, add it
        If Not (String.IsNullOrEmpty(tempString)) AndAlso Not (aList.Contains(tempString)) Then
            aList.Add(tempString)
        End If

        ' Tear off a letter then recursify it
        For i As Integer = 0 To tempString.Length - 1
            GetListofLetters(tempString.Remove(i, 1), aList)
        Next
    End Sub

    Private Function Alphabetize(ByVal aString As String) As String
        ' Turn into a CharArray and then sort it
        Dim aCharArray As Char() = aString.ToCharArray()
        Array.Sort(aCharArray)
        Return New String(aCharArray)
    End Function

End Class
Public Class ListSorter
    Implements IComparer(Of String)

    Public Function Compare(ByVal x As String, ByVal y As String) As Integer Implements System.Collections.Generic.IComparer(Of String).Compare
        If x.Length = y.Length Then
            Return String.Compare(x, y)
        Else
            Return (x.Length - y.Length)
        End If
    End Function
End Class

我可以提供以下解决方案 - 还不是很完善,并不快,而且它假定输入是一组,因此不包含重复的项目。我将在以后添加一些解释。

using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
   static void Main()
   {
      Int32 n = 5;
      Int32 k = 3;

      Boolean[] falseTrue = new[] { false, true };

      Boolean[] pattern = Enumerable.Range(0, n).Select(i => i < k).ToArray();
      Int32[] items = Enumerable.Range(1, n).ToArray();

      do
      {
         Int32[] combination = items.Where((e, i) => pattern[i]).ToArray();

         String[] stringItems = combination.Select(e => e.ToString()).ToArray();
         Console.WriteLine(String.Join(" ", stringItems));

         var right = pattern.SkipWhile(f => !f).SkipWhile(f => f).Skip(1);
         var left = pattern.Take(n - right.Count() - 1).Reverse().Skip(1);

         pattern = left.Concat(falseTrue).Concat(right).ToArray();
      }
      while (pattern.Count(f => f) == k);

      Console.ReadLine();
   }
}

它生成确定如果一个元素属于当前组合开始k倍布尔模式的序列真(1)在最左侧,其余所有假(0)。

  n = 5  k = 3

  11100
  11010
  10110
  01110
  11001
  10101
  01101
  10011
  01011
  00100

下一个图案被如下生成。假设当前的模式是以下内容。

00011110000110.....
从左至右

扫描并跳过全零(假)。

000|11110000110....

进一步扫描整个的人的第一个块(真)。

0001111|0000110....

移动所有除了最右边的一个回跳过那些最左侧。

1110001|0000110...

和最后移动至最右边的一个跳跃的单一位置到右侧。

1110000|1000110...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top