Tackling permutations and recursion one step at a time.
Solving a permutation problem with recursion has been particularly difficult for me to wrap my head around. It just doesn’t seem as natural as iteration. So let’s take a gentle journey, you and me. We’ll walk through a recursive solution together. Step-by-step.
This is my dog Lula. Dog’s are comforting. So let’s think of cute fluffy pups while thinking of scary weird algorithms.
Lula’s a sweetie. A smartie pants. A loud barker. Let’s permute Lula. Or…her species. Or…the word “dog”. Let’s write a function that takes in a string (dog) and outputs every combination possible of that word in an array.
But first, let’s note how we do this manually. How would we permute “DOG”? Here’s one approach:
- Let’s take the first letter in put it in our memory: D
- Now, let’s take the remaining letters: O, G
- Let’s make one word that takes the remaining letters and adds them to our first letter one by one: D+ OG, and D+ GO. So we now have 2 permutations: DOG, and DGO.
- Let’s move on to the second letter: O, and take the remaining letter and set them aside: D and G.
- Let’s make a permutation of those: O + DG, O + GD. Now we have 4 permutations: DOG, DGO, ODG, OGD.
- Now let’s tackle the last letter: G. And set aside the remaining letters: D and O.
- Let’s make permutation of that: G + DO, and G + OD. Now we have 6 permutations: DOG, DGO, ODG, OGD, GDO, GOD.
- We’d now just have to return all these combinations in an array.
Notice what we’re doing here:
- We’re taking the word, and iterating through it one letter at a time.
- We then take the remaining letters, and iterate through those remaining ones, one letter at a time.
- When we’re down to one letter, we add it to that first letter we took a look at.
- We keep doing this until we’ve done this with all letters.
This is recursion. Let’s code it up using JavaScript.
#recursion #permutations #javascript #programming