meteorBuzz
meteorBuzz

Reputation: 3200

Recursive functions returns expected string value and sometimes undefined?

The function randomly works as expected, and sometimes returns undefined. That is what I do not understand.

Can someone explain how javascript performs when it repeats function calls, for this example, in a recursive pattern.

The main function takes two arguments

First Arg: an integer which represents the number of characters it will take from the second argument. Second Arg: A string.

The entire code

var getRandomIntInteger = function (min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function recursive(arr, string, limit) {

    if (string.length >= limit) {
        return string
    }
    else {
        // get random integer within the range of the array ength
        var randIndex = getRandomIntInteger(0, arr.length)
        // concatenate that value sitting at that index
        string += arr[randIndex]
        // remove that value from the array
        arr.splice(randIndex, 1)
        // re-run
        return recursive(arr, string, limit)
    }

}

var main = function(k, i) {
    let inputArray = Array.from(i)
    console.log('k=',k, 'inputArray length = ', inputArray.length)


    if (k >= i.length) {
        return 'sameple size must not exceed '
    }
    let s = ""
    var res = recursive(inputArray, s, k)
    console.log('result = ', res)
    return res

}

// run the function
main(4, "ABCDEFGHI")

This function call sometimes returns 4 random charactors and sometimes returns undefined even if the function is called with the same arguments.

Upvotes: 0

Views: 87

Answers (1)

trincot
trincot

Reputation: 350290

By the manner you have defined your random function you should change this call:

 var randIndex = getRandomIntInteger(0, arr.length)

to this:

var randIndex = getRandomIntInteger(0, arr.length - 1)

... since the second argument is a number that could be produced by getRandomIntInteger, yet arr[arr.length] is always undefined.

Upvotes: 1

Related Questions