Thursday, 23 August 2012

Some Simple Programming Problem - Made Hard

Well, its time for me to introduce you to the most difficult programming logic question of all time:

Given a string s we need to find out all the permutations of the characters of that string. Pretty easy huh?

Well lets add something to it. You are only allowed to use 2 for loops. That's it. No more loops. :-/

So here is the solution. Recursion!! 

Code: VB

Function Permute(ByVal str As String) As List(Of String)
        Dim ret As New List(Of String)
        Dim q As Char() = str.ToCharArray

        Dim n As String = ""
        If q.Length <> 1 Then
            For i = 0 To q.Length - 1
                n = q(i)

                Dim a As List(Of String) = Permute(str.Remove(i, 1)) ' Recursion!!
                For Each el In a
                    ret.Add(n & el)
        End If

        Return ret
    End Function

No comments:

Post a Comment