Puzzled

just how in the ... does this work,I have spent 2 hours literally drawing this out on paper and I just can't see how this code works

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  #include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int l, int r)
{
   int i;
   if (l == r)
      cout << a << endl;
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i)); //backtrack
       }
   }
}

/* Driver program to test above functions */
int main()
{
    char str[] = "JOE";
    int n = strlen(str);
    permute(str, 0, n-1);
    return 0;
}


this is the output




JOE
JEO
OJE
OEJ
EOJ
EJO






but when I draw it out on paper I just keep getting Joe printed,and only happens about 3 times I just don't understand how it works especially this block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void permute(char *a, int l, int r)
{
   int i;
   if (l == r)
      cout << a << endl;
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i)); //backtrack
       }
   }
}


L = 0 , r = 2, i = L = 0 so i = 0

what is the point of swapping (a+1) = 'e' with a+i which is also 'e'

then a recursive call to permute which essentially does the same

L will always be = to i until it hits 2 then the for loop doesn't execute

I just don't see how in the blue earth this works

very very very confused and that is an under statement everything I thought I knew about problem solving and programming is up in the air now,

I have even drawn out the stack and followed the function calls on paper and kept track of all the variables and their values but it's just not working


what is the point of swapping (a+1) = 'e' with a+i which is also 'e'

It is not a + 1 it is a + l

One doesn't need to code a special case to avoid swapping when l and i are the same, simplifying the algorithm - that is the point.

You could do this:

1
2
3
4
5
6
7
8
       permute(a, l+1, r);
   	
       for (i = l+1; i <= r; i++)
       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i)); //backtrack
       }


in place of the loop and get the same result.
thanks cire much appreciated

I still can't figure out how and where the swapping occurs
Topic archived. No new replies allowed.