DEV Community

Vadim Stakhnyuk
Vadim Stakhnyuk

Posted on

5 2

Persistence Algorithm and A Simple Introduction To .reduce()

As my hunt for a job position continues, so does my Algorithm practice. Day after day I am introduced to new concepts and learn new ways to solve problems. This time around, while working on the CodeWars "Persistent Bugger" algorithm, I learned about the Javascript .reduce() function and implemented it into my algorithm successfully.

The .reduce() function has a lot of working pieces, and is extremely useful for solving mathematical problems. To start, we can say that .reduce() takes an input and combines it and returns the input but in combined form. For example, an input of an array of numbers can be returned as a sum with the .reduce() function. In the "Persistent Bugger" algorithm, that is exactly what I was doing.

Let's start with the basic functionality of the .reduce() function and how it is set up. I will setup an example with an array of numbers, and I will return the sum of these numbers. This is a great way to display the functionality of the reduce function.

  • The .reduce() function receives an input of an array of numbers
let numbers = [1, 2, 4, 5];

let total = numbers.reduce((sum, currentValue) => {
   return sum + currentValue;
});

console.log(total)
Enter fullscreen mode Exit fullscreen mode
  • We call the reduce function on our array of numbers with 2 arguments.

  • The first argument is the sum, which will be initialized to the first value of the array.

  • The second argument is the current value.

  • Inside our function, we return the sum of the current value added to our total.

This is a simple example of how the reduce function works. Although you can call the reduce function with more arguments, this is a simple explanation and example of the function at work.

Now, we can take a look at the algorithm. This is a great algorithm, and was definitely fun to solve. Basically, the input is a number as a string. You have to find the multiplicative persistence of that number. This means you have to keep multiplying the number until the return number is a single digit.

Let's say our function is called persistence, here is a look at some example inputs and outputs.

1.) persistence(39) === 3

  • 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4. We had to multiply 3 times in order to reach a single number. Therefore, the answer is 3.

2.) persistence(999) === 4

  • 9 * 9 * 9 = 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, 1 * 2 = 2. Four calculations to reach a single number.

The approach I took to solving this algorithm started with the parseInt function where I took a string and turned it into a number. Then I split that number so that my input could be an array of numbers. Then I initialized a count variable so that I could count how many times I multiplied the input. I also declared a total variable. This variable is the input that was passed into the .reduce() function.

function persistence(num) {
    // change the number into a string and 
    // split the number into individual numbers.
    var numArray = num.toString().split('');

    // Initialize a count variable to count its
    // multiplicative persistence.
    let count = 0;

    // Initialize a total variable.
    let total;

    // While loop to make function run only when the split
    // number has more than 1 element.
    while (numArray.length > 1) {

        // Set the total variable equal to the reduce function
        // which gets the sum and gets multiplied by the current
        // value in the loop.
        total = numArray.reduce(function (sum, currentValue) {
            return sum * currentValue;
        })

        // Increment the count variable
        count++;

        //split the new number and reset the function.
        numArray = total.toString().split('');
    }

    // If the new number is no longer greater than 1,
    // then that means we reached the end.
    // Return the count.
    return count;
}
Enter fullscreen mode Exit fullscreen mode

That is a short introduction to the reduce function as well as my little journey into discovering it. Also, how I used the reduce function to solve my algorithm. This "Persistent Bugger" algorithm is a fun to solve algorithm and shows a new way to calculate numbers.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay