Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
this code is recursive combination.
so i wanna convert to Non-recursive one.
plz..help me..

my code is..

C++
#include <iostream>
using namespace std;
 
void comb(int n, int r, int *arr, int sz) {
    for (int i = n; i >= r; i --) {
        // choose the first element
        arr[r - 1] = i;
        if (r > 1) { // if still needs to choose
            // recursive into smaller problem
            comb(i - 1, r - 1, arr, sz);
        } else {        	
            // print out one solution
            for (int i = 0; i < sz; i ++) {
                cout << arr[i] << " ";
            }
            cout << endl;
        }
    }
}
 
int main() {
    const int N = 4;
    int *arr = new int[3];
    for(int i=1;i<=N;i++)
    	comb(N, i, arr, i);
    return 0;
}


*Result
1
2
3
4
1 3
1 2
1 4 
2 3 
2 4
3 4
1 2 3
1 2 4
1 3 4
2 3 4
1 2 3 4
Posted
Updated 3-Mar-15 9:01am
v3
Comments
Sergey Alexandrovich Kryukov 2-Mar-15 19:39pm    
The word "convert" makes no sense here. You just need to forget recursive version, formulate what you need to achieve, strictly, formally, precisely, and explain what prevents you from writing a non-recursive version, what have you tried so far?

The puzzles with reading and interpreting the goal through the source code could be funny, even useful for training (rarely), but, honestly, in this case, hardly interested to anyone.

—SA

1 solution

This is universal help for all of your homework problems - not only for this problem but any computing problem.

  • Determine what the problem is

  • Determine what steps you would go through to solve with pencil and paper

  • Determine which parts are repetitive


Now, convert to code by using the meaning of code: convert one description to another.
(your manual process for equivalent programming steps).

Now, after debugging for typos and such, you should have a working (although not optimal) solution.

Now - start to become smarter by optimizing steps. This comes with experience. This does not come from have other people do your assignments.

By analogy, this works for the world outside of programming.

 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 3-Mar-15 14:38pm    
Come to think about, this is a good advice in this case, 5ed.
—SA
Matt T Heffron 3-Mar-15 19:28pm    
+5Similar to my advice on http://www.codeproject.com/Questions/882177/How-do-I-create-a-function-using-recusion-and-coun

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900