Jump to content

how write a new function without recursion call


Recommended Posts

Hi at all,

please read this function:

            function cc(letters, comb, m, k) {

var ret=[];
                if (k == 0) {
                } else {
                    for (var i=m; i<= letters.length-k; ++i) {
                        cc(letters, comb+"  "+letters+' ', i+1, k-1);

return ret;

Function cc() calc combinations of numbers or letters or any other object like words, colors ........ .

to call cc():

var c=new Array(1,2,3,4,5,6,7,8,9);// it can be  an array of letters or of any other object

var k=3;//size of any combination that can be 2 or 3 or 4 ...... or more

var start=0;


var r=cc(c,"",start,k);

It work very well but I do not love recursion call.
How can I do to obtein the some result without recursion call?
Thank you very much

Link to comment
Share on other sites

In an easy way?  No.  You need nested loops, and the number of loops you write is going to set a maximum value for parts of what the function can do.  Recursion is how you avoid that, you can use a much more elegant piece of code to do that kind of thing if you use recursion.  The code you posted doesn't actually do anything though, it never returns a value other than an empty array when k is greater than 0.  It might have gotten messed up because you didn't post it in a code box, maybe there's something left out, I'm not sure.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...