Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
January 14th, 2013, 10:20 AM
 ZWEI01
Registered User

Join Date: Jan 2013
Posts: 10
Time spent in forums: 5 h 54 m 13 sec
Reputation 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) {
} 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
January 14th, 2013, 11:10 AM
 Jacques1
You have been warned

Join Date: Jul 2012
Posts: 3,088
Time spent in forums: 2 Months 3 Weeks 4 Days 1 h 42 m 39 sec
Reputation Power: 1063
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.
ZWEI01 agrees!

 Viewing: Dev Shed Forums > Web Design > JavaScript Development > Recursive Function Help (newbie)