How to solve the Help the bookseller! kata.

A nice kata to solve in 10 minutes or less. Help the bookseller!

How to solve the Help the bookseller! kata.
Photo by Walling / Unsplash

The link to begin with.

Background Story

Photo by Jason Goodman / Unsplash

I'm waiting for my Team Retrospective to start as we're near to the end of the current sprint. Seeing I have a few minutes left, I go to the CodeWars platform to see if there's an interesting kata I can solve in 10 minutes or less.

The Help the Bookseller problem looks interesting enough that challenge you in your Data Structure knowledge.

As usual, there are multiple ways of solving this kata including the use of a hash or dictionary or a simple array.

I choose to use a hash because it makes the most sense in my mind right away and the use of hashes is performant.

Another way of course is to use a Struct to keep the values.

Potential Solution

def stock_list(listOfArt, listOfCat)
  cat_num = {}

  listOfCat.map do |cat|
    listOfArt.each do |art|
      cat_num[cat] = 0 unless cat_num[cat]
      cat_num[cat] += art.split.last.to_i if art.start_with?(cat)
    end
  end

  cat_num.map { |k, v| "(#{k} : #{v})" }.join(' - ')
end

Similarly, here's the same solution written in JavaScript:

function stockList(listOfArt, listOfCat) {
  const catNum = {};

  listOfCat.map((cat) => {
    listOfArt.map((art) => {
      if (art.startsWith(cat)) {
        catNum[cat] = catNum[cat] || 0;
        catNum[cat] += parseInt(art.split(' ')[1]);
      }
    });
  });

  return Object.keys(catNum)
    .map((k) => `(${k} : ${catNum[k]})`)
    .join(' - ');
}

Conclusion

Working on these types of programming challenges helps to keep your mind sharp and also helps you to think about the problem differently. I only thought about the use of Hash or array initially and the increment of the value.

Possible improvements are:

  • use of structs giving a more OOP approach
  • use of sum method to sum the values of the array
  • use of reduce method to sum the values of the array

You can write this solution in a single line but I prefer making it more readable and showing the intent.

A nice kata to solve in 10 minutes or less.