を出すにはどうしたらいいんで組み合わせの要素のリスト<T> ます。NET4.0

StackOverflow https://stackoverflow.com/questions/1119699

質問

あると思いますが、どのようにするには、類似しているが同一ではない、一つの回答 こちらです。

私のような機能をすべての k組み合わせの要素のリストからnます。ご注意い組み合わせない順列は、私達に必要な解決策を変 k (ハード-コーディングのループはなかった。

いソリューションa)、b)できるコードにVB10/.純4.0の製品をご用意しています。

このソリューションを必要とLINQ、b)その利用にC#の"量"コマンドはいません。

の組み合わせは重要ではありません(つまり、辞書的なグレー-コードをいいます)は、優雅さはその性能が実行されている。

の存とC#のソ こちらの が完璧なものしか開発されておらず、コード化にVB10.)

役に立ちましたか?

解決

コード K の要素の配列として組み合わせのリストを生成する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なる再帰り、再帰的解決にはなる...との組み合わせにより組みが容易に得られるため、単なる尊重の順序を入力します。

その組み合わせの項目のリストLのN項目について:

  1. noneの場合、K>N
  2. 全体のリストLの場合K==N
  3. さK < N,その後の二房:を含むものについての最初の項目のLとの組み合わせK-1のN-1項目プラスの組み合わせのその他のN-1です。

に擬似コード(使用例です。サイズをリストの長さ[]として空のリスト.追加項目を追加するには、リスト、.ヘッド一覧を取得するための最初の項目.テール一覧の取得を"すべてのもの"の項目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:])

る必要があるかにかかわらず冗長化構築リストによる繰り返します。追加で簡潔に構築してリストの内包表記は、構文の詳細(としてのヘッド、テールvsリストスライス表記の最初の項目のリストvsの他):の擬似コードが表も同じ考えであるにも同じ考え方と前から整理します。.実践できるので、どの言語でできる再帰(もちろん、最小限のリスト操作!-).

私のねじれ、長さによって最初にソートされたリストを、提供する - その後、アルファで

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.....

左から右へスキャンし、すべてゼロ(false)をスキップします。

000|11110000110....

のもの(真)の最初のブロックの上にさらにスキャンします。

0001111|0000110....

は戻って非常に左に、右端の1以外のすべてスキップされたものを移動します。

1110001|0000110...

そして最後に一番右に移動するには、右に1つの位置をスキップします。

1110000|1000110...
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top