Recursion

From bibbleWiki
Jump to navigation Jump to search

Introduction

Want to get done the basics for some of this.

Why

Breaks down large chunks into smaller chunks.

When

You use it when problems contain smaller instances of the same problem. E.g. finding how many combinations there are of n items.

Aspects of Recursion

They all have a

  • base case
  • recursive case

Base Case

This is where the smallest instance of the case can be solved easily. E.g. For number of combinations when the array is empty.

Recursive Case

This is an instance of the problem that shrink the size of the input toward the base case.

Example Factorial

<syntaxhightlight lang="js"> const factorial = (n) => {

   if(n === 1) return 1
   return n * factorial(n-1)

} </syntaxhightlight>

Example Palindrome

<syntaxhightlight lang="js"> const palindrome = (str) => {

   console.log("calling with",str)
   if(str.length === 0) return true
   if(str.length === 1) return true
   if(str[0] !== str[str.length-1]) return false
   
   return palindrome(str.substr(1, str.length-2))

} </syntaxhightlight>