DrStrangeLove
DrStrangeLove

Reputation: 11557

Recursive strings output

I have this code:

var al = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

function output(a, ind) {
    if (!ind) {
        ind = 0;
    }

    if (ind < 26) {
        var newtext = document.createTextNode(recursString(a[ind], ind));
        var br = document.createElement("br");
        var para = document.getElementById("hello");
        para.appendChild(newtext);
        para.appendChild(br);

        output(a, ++ind);
    }
}

var iter = 0;
var s = "";

function recursString(str, i) {
    if (i === 0) {
        s += str;

        return s;
    }

    if (iter < i) {
        s += str;
        iter++;

        recursString(str, i);
    }

    return s;
}

It outputs strings like this:

A
AB
ABC
ABCD
ABCDE
etc.

But i need:

A
BB
CCC
DDDD
EEEEE
etc.

I need to use only recursion. I suspect, according to debugging, s variable doesn't work like it should.. How do i fix it to make it work the way i want?

Upvotes: 1

Views: 1642

Answers (2)

matehat
matehat

Reputation: 5374

Forgetting about the global variables iter and str, you could replace the last function with :

function recursString(str, ind) {
  return ind == 0 ? str : str+recursString(str, --ind);
}

This can be rewritten in a more expanded form like this :

function recursString(str, ind) {
  if (ind == 0)
    return str;
  else {
    ind -= 1;
    return str + recursString(str, ind);
  }
}

Upvotes: 2

pimvdb
pimvdb

Reputation: 154838

You should append the same letter each time, and stop when the length is the index of the letter in the alfabet + 1: http://jsfiddle.net/5h4sX/.

Note that you're currently changing the variables outside the function. You could also pass them along with each recursive call, but you don't need to if you want to keep it more understandable.

var str = "",
    iter = 0;

function recursString(letter, totalLength) {
    str += letter; // add letter

    if (iter === totalLength) { // stop recursing
        return str; // return what we have built up
    } else if (iter < totalLength) {
        iter++; // increment iteration variable
        return recursString(letter, totalLength); // return the result of a recursive call
    }
}

You do need to reset the variables before each recursive call though:

str = "";
iter = 0;
var newtext = document.createTextNode(
    recursString(a[ind], ind)
);

Upvotes: 3

Related Questions