Recursion (slightly off-topic)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gaijinco

    #1

    Recursion (slightly off-topic)

    I'm trying to convert this:

    for(int i=0; i<5; ++i)
    for(int j=0; j<5; ++j)
    for(int k=0; k<5; ++k)
    cout << i+1 << j+1 << k+1 << endl;

    Into a recusive function. But I ended with:

    #include <iostream>
    using namespace std;

    void permute(int);
    int A[3];

    int main(){

    permute(0);

    return 0;
    }

    void permute(int n){

    for(int i=0; i<5; ++i){

    A[n]=i+1;

    if(n<3){
    permute(n+1);
    } else {
    for(int j=0; j<3; ++j)
    cout << A[j];
    cout << endl;
    }
    }
    }

    Which doesn't work! I'm lost here, could anyone give me a clue?

  • Rade

    #2
    Re: Recursion (slightly off-topic)

    > if(n<3){

    Probably:

    if (n+1 < 3) {


    Comment

    • John C

      #3
      Re: Recursion (slightly off-topic)


      You are very close! (but it's late and being the Saturday of a very long
      week, there is drinking involved)

      Shouldn't that be if(n<2)? If n==2 you will call permute(3) which will
      cause A[3] = I+1; and there ain't no A[3]

      On 11/19/05 8:37 PM, in article
      1132454245.5962 88.14660@g49g20 00...legro ups.com, "Gaijinco"
      <gaijinco@gmail .com> wrote:
      [color=blue]
      >
      > void permute(int n)[/color]
      {[color=blue]
      >
      > for(int i=0; i<5; ++i)[/color]
      {[color=blue]
      >
      > A[n]=i+1;
      >
      > if(n<3) ////////////////////// if (n<2) here[/color]
      {[color=blue]
      > permute(n+1);
      > }[/color]
      else
      {[color=blue]
      > for(int j=0; j<3; ++j)[/color]
      {[color=blue]
      > cout << A[j];[/color]
      }[color=blue]
      > cout << endl;
      > }
      > }[/color]
      }

      Comment

      Working...