简体   繁体   中英

I am trying to better understand recursion by using the FizzBuzz problem in javascript

I don't understand line 18? If the input is 100 how does program print out the number 1 first and end with the number 100 in the array? Any help would be appreciated.

 function fizzBuzz(n){ //create empty array called results //create base case for when n === 1 //recurse and push value to array var results = []; if(n === 1){ return [1]; } else { if(n % 3 === 0 && n % 5 === 0){ results.push('FizzBuzz') } else if (n % 3 === 0){ results.push('Fizz') } else if (n % 5 === 0){ results.push('Buzz') } else { results.push(n); } return fizzBuzz(n - 1).concat(results); // ??? } } console.log(fizzBuzz(100)); 

It creates a results array with the last value (for 100 ) first, then recursively creates another array with the results for the values from 0 to 99 , and in the end concatenates them in the right order.

You are right, this is confusing. A much better recursive implementation would be

function fizzBuzz(n) {
  if (n <= 0) {
    return [];
  }
  var results = fizzBuzz(n - 1);
  if (n % 3 === 0 && n % 5 === 0) {
    results.push('FizzBuzz');
  } else if (n % 3 === 0) {
    results.push('Fizz')
  } else if (n % 5 === 0) {
    results.push('Buzz')
  } else {
    results.push(n);
  }
  return results;
}

console.log(fizzBuzz(100));

The first thing to realize is that every call to fizzBuzz returns an array - it does not add to an existing array, it creates a new one every time.

So, if the input n is 1, it simply returns a single-element array with 1 in it.

If n > 1, there will be a recursive call. "results" has already been created as an empty array, so the .push() statements add a single element to that array:

If n is divisible by 3 and 5, the array will be ['FizzBuzz'] If n is divisible by 3 only, the array will be ['Fizz'] If n is divisible by 5 only, the array will be ['Buzz'] Otherwiese, the array will be [n] whatever n is.

Since n > 1 (or we wouldn't be here) we have to call FizzBuzz again with the next-lower n and concatenate its result to ours. This is how the long array is built - by concatenating the array returned from recursive calls to FizzBuzz.

This line

fizzBuzz(n - 1).concat(results);

could be interpreted as "append the results we have just gathered for n to the results we generated for f(n - 1) ." "Append a to b" means "put a after b." Think what this would do for n == 2 , then generally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM