Weekly Coding Challenge: Sum of Minimums! – written in JavaScript and Python

Posted by

2 min read ~ Hello readers! It’s really important for me to continue my practice and learning. Lately, I have been completing a coding challenge a day with codewars. This helps me keep my skills sharp and see how other devs all over the planet would solve these problems. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today. the problem set focuses on JavaScript and Python and some of the important functions that we can leverage in our applications. Today, this one is pretty simple yet a useful exercise!

Sum of Minimums!

Given a 2D list of size m * n. Your task is to find the sum of minimum value in each row.

For Example:

[
  [1, 2, 3, 4, 5],       # minimum value of row is 1
  [5, 6, 7, 8, 9],       # minimum value of row is 5
  [20, 21, 34, 56, 100]  # minimum value of row is 20
]

So, the function should return 26 because sum of minimums is as 1 + 5 + 20 = 26

Note: You will be always given non-empty list containing Positive values.

JavaScript solution:

function sumOfMinimums(arr) {
    // reduce the function and grab the min of the arr starting at 0
    return arr.reduce( (acc, cur) => acc + Math.min(...cur), 0);
}

Python solution:

def sum_of_minimums(numbers):
    # return the sum of a map with the minimum output for numbers
    return sum(map(min, numbers))

Disclaimer: *Now, as much as I am tempted to use ES8 & ES9 functions to reduce the number of lines in JavaScript, I am always a fan of readable code that others can understand. Therefore, with the JavaScript examples, I will try to write it without fancy functions as much as possible so it can actually be read and absorbed by my readers. All of my solutions are commented to explain my thinking. Of course, they could always be better. Please feel free to share how you would solve it!*

All credit to problem sets goes to codewars

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s