0

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.

2
  • 1
    Where is the debugging trace? You should be able to show us the numbers you get from getRandomInteger, the values of the arguments as seen inside each routine, etc. Commented Mar 28, 2017 at 15:46
  • what language is it? you should add the language tag Commented Mar 28, 2017 at 16:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.