#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Recursive Function Help (newbie)


    Well, I'm currently in the process of learning JS, and I started to write a unscramble-word game last night. Problem is the function I wrote to scramble a word keeps returning undefined and after much frustration I need some help.

    Code:
    	function scramble (toScramble, recursions) {
    		//Condition. scrambles word 5 times.
    		if (recursions == 5) {
    			return toScramble;
    		} else {
    			recursions++;
    			var size = toScramble.length - 1;
    			//Get random index to select random split letter
    			//from string.
    			var index = Math.floor(Math.random() * size);
    			var splitArray = toScramble.split(toScramble[index]);
    			//Add split letter back to new array to maintain word.
    			splitArray + toScramble[index];
    			
    			var size = splitArray.length - 1;
    			newString = "";	
    			for (var i = size; i >= 0; i--) {
    				//Cocacenate word backwards with for loop.
    				newString += splitArray[i];
    				if (i == 0) {
    					scramble(newString, recursions);
    				}
    			}
    		}
    }
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    you're missing a "return" for the recursive function call. Without that, the whole recursion doesn't work, because the final value doesn't get passed on. The "original" function call simply returns nothing, so you end up with "undefined".

    There are several other logical errors and Javascript mistakes:
    Code:
    splitArray + toScramble[index];
    This line by itself doesn't do anything, because it's an expression like "1 + 1". Without an assignment, it's just discarded. The value of the expression also isn't correct, because you add a string to an array. This yields a nonsense string like "ab,def". I guess you meant something like this:
    Code:
    splitArray.push(toScramble[index]);
    However, there's a logical error: When the split character occurs multiple times and you only add it once at the end, all the characters except one get lost.

    It might be a good idea to start with a simpler recursive function to understand the concept. A classical example would be the factorial function: fac(n) = 1 * 2 * ... *n
    Code:
    function fac(n) {
    	if (n == 0)
    		return 1;					// base case
    	else
    		return n * fac(n - 1);		// recursive call
    }
    You can also try to recursively revert an error.

    Comments on this post

    • ZWEI01 agrees

IMN logo majestic logo threadwatch logo seochat tools logo