DEV Community

Bridget Amana
Bridget Amana

Posted on

Building a Word Scrambler with JavaScript (part 1)

I started a little project—a word unscrambler, for anyone who’s not familiar, a word unscrambler is a tool that takes a scrambled string of letters and generates all possible valid words that can be formed from those letters, If you’re a Word Cookie fan who has cheated once or twice, you’ll know what I’m talking about.

Today's Goal is to write a function that generates every possible combination of letters, valid words or not. It’s all about generating the raw material before filtering for actual words. I’m super excited to walk you through the very first step of what I did!
So let’s get started.

Step 1: Setting the Stage (HTML & CSS)

Before we get into the code, here’s what the HTML and CSS look like.

<input type="text" id="scrambledInput" placeholder="Enter a word">
<button id="unscrambleButton">Unscramble</button>

<div id="resultsContainer"></div>
Enter fullscreen mode Exit fullscreen mode

And here’s a bit of simple CSS:

#scrambledInput, #unscrambleButton {
    margin: 10px;
    padding: 10px;
    font-size: 16px;
}

#unscrambleButton {
    border: 0;
    color: white;
    background-color: blueviolet;
}

#resultsContainer {
    margin-top: 20px;
}

ul {
    list-style-type: none;
    display: grid;
    grid-template-columns: repeat(6, 1fr);
}

Enter fullscreen mode Exit fullscreen mode

This sets up a basic input field, a button, and an area where we’ll display the scrambled words. Nothing too fancy yet!

Step 2: Getting the Permutations

So, the task is to take a word (scrambled or not), and show all possible permutations of the letters. I was excited to dive into this. This article was a really big help JavaScript Program to Print All Permutations of Given String.

Here’s the code I wrote for generating permutations:

function generatePermutations(inputString) {
    const uniquePermutations = [];

    function generateUniquePermutations(arr, currentIndex) {
        if (currentIndex === arr.length - 1) {
            uniquePermutations.push(arr.join(""));
        } else {
            for (let i = currentIndex; i < arr.length; i++) {
                [arr[currentIndex], arr[i]] = [arr[i], arr[currentIndex]];
                generateUniquePermutations([...arr], currentIndex + 1);
            }
        }
    }    generateUniquePermutations(inputString.split(""), 0);
    return uniquePermutations;
}
console.log(generatePermutations('abcd')) //test out with other word

Enter fullscreen mode Exit fullscreen mode

Let’s break it down step-by-step:

  • Step 1: I created a function called generatePermutations that accepts the input string we want to scramble.

  • Step 2: Inside this function, there’s another helper function called generateUniquePermutations. It does the actual scrambling, starting with the letters of the word, swapping them around, and storing each unique combination.

  • Step 3: Every time we reach the last index of the word (which means the word is fully scrambled), it pushes that version of the word into the array uniquePermutations.

  • Step 4: Finally, console.log the function with your preferred word.

Step 3: Realizing I Had a Problem

Everything seemed perfect at first, but when I started testing with different words, I quickly noticed that some of the results were repeated words. This was an issue! For example, when I scrambled the word "dogo", since it has two “o” it was showing duplicate permutations like

  • "dgoo"
  • "odog"
  • "odgo"
  • "dgoo" (again!)

Scrennshot of my console

I had to figure out how to remove duplicates so the final list would only show unique words.

Step 4: Fixing the Repeats

To handle the duplicates, I tweaked the code a little bit. Here's what I did

function generatePermutations(inputString) {
    const uniquePermutations = [];

    function generateUniquePermutations(arr, currentIndex) {
        if (currentIndex === arr.length - 1) {
            const newPermutation = arr.join("");
            if (uniquePermutations.includes(newPermutation)) {
                uniquePermutations.push(newPermutation);
            }
        } else {
            for (let i = currentIndex; i < arr.length; i++) {
                [arr[currentIndex], arr[i]] = [arr[i], arr[currentIndex]];
                generateUniquePermutations([...arr], currentIndex + 1);
            }
        }
    }

    generateUniquePermutations(inputString.split(""), 0);
    return uniquePermutations;
}
console.log(generatePermutations('dogo'))
Enter fullscreen mode Exit fullscreen mode

What changed? I added a condition to check if the permutation already exists in the array. If it doesn’t, it gets added—problem solved!
I thought I had solved this issue, but I got an empty array instead. If anyone reading this has any ideas on how to improve my code and get rid of these duplicates, I’d love to hear your suggestions.

Step 5: Displaying the Scrambled Words

The final step is showing the scrambled words on the page. Here’s the code that listens for a button click and displays the results:

function unscrambleWords() {
    const input = document.getElementById('scrambledInput').value;
    const combinations = generatePermutations(input);
    displayResults(combinations);
}

function displayResults(combinations) {
    const resultsContainer = document.getElementById('resultsContainer');
    resultsContainer.innerHTML = '';

    const wordList = document.createElement('ul');
    combinations.forEach(word => {
        const listItem = document.createElement('li');
        listItem.textContent = word;
        wordList.appendChild(listItem);
    });
    resultsContainer.appendChild(wordList);
}

document.getElementById('unscrambleButton').addEventListener('click', unscrambleWords);

Enter fullscreen mode Exit fullscreen mode

Here’s what happens:

  • unscrambleWords: Grabs the word from the input field, passes it to our generatePermutations function, and gets all the scrambled words.
  • displayResults: Takes all those permutations and creates a list in the browser, so the user can see them.

That’s it for the first step and here’s the link to try it out

If you’ve stuck with me this far, still stick around for part 2.

Top comments (0)