2

So I am converting an extension method to find permutations of a generic list from c# to vb The code in c# does not return duplicate. For example: {1,2} is same as {2,1} and {1,1} is not allowed. The vb code that I convert, however gives me a duplicate. Can someone help me spot the problem. I got the c# code from accepted answer in this thread: How to Generate Combinations of Elements of a List<T> in .NET 4.0

Here is the vb code:

Module HelperPermutation
<Extension()>
Public Function Combinations(Of T)(elements As IEnumerable(Of T), k As Integer) As IEnumerable(Of T())
    Dim result As List(Of T()) = New List(Of T())
    If (k = 0) Then
        result.Add(New T(-1) {})
    Else
        Dim current As Integer = 1
        For Each element In elements
            result.AddRange(elements _
                            .Skip(current = current + 1) _
                            .Combinations(k - 1) _
                            .Select(Function(c) (New T() {element}).Concat(c).ToArray())
                            )
        Next
    End If
    Return result
End Function
End module

I tried to add Distinct but it still gives me duplicates. And this is my console app to use that extension method:

Dim list As New List(Of Integer) From {1, 2, 3}
    Dim array = list.Combinations(2)
    Console.WriteLine("# of permutation: " & array.Count)
    For Each value In array
        Console.WriteLine("-------Pairs: " & value.Count)
        For i As Integer = 0 To value.Count - 1 Step 1
            Console.WriteLine("value = " & value.ElementAt(i))
        Next
    Next

    Console.ReadLine()
Community
  • 1
  • 1
ngunha02
  • 1,689
  • 1
  • 18
  • 23
  • Does the line `.Skip(current = current+1)` really give the equivalent value of `.Skip(current++)`? I could see that evaluating to a boolean equivalent comparing whether current is equal to current+1 (false) – Dan Drews Feb 11 '15 at 00:55
  • Yea, it current = current + 1 does not work. – ngunha02 Feb 11 '15 at 00:59

1 Answers1

2

current = current + 1 is not doing assignment. It's an equality test, so the result of that expression is boolean. Since there is no overload for Skip() that takes a boolean, it seems like you might not be using Option Strict. I would highly suggest using it for spotting mistakes like this.

There is no post-increment built into the VB language, but luckily, you can create your own.

Function PostIncrement(ByRef arg As Integer) As Integer
    arg += 1
    Return arg - 1
End Function
recursive
  • 77,417
  • 29
  • 137
  • 228
  • Yeah, the current = current + 1 does not do the assignment. Oops. I am new to vb, so let me try out with post increment and let you know! – ngunha02 Feb 11 '15 at 01:02