Categories
Code challenges Programming

30 Days of Code #7

In which I solve one problem in two different ways.

I gave myself a day off yesterday since I took a deep dive into how to use APIs for Google Maps. I enjoyed the deep dive, but I’m happy to be back on track with my coding challenge.

This problem might count as two, anyway, since I did it in two different ways. The first time I did the problem, I used arrays as my primary data structure, and the second time I used a hash object.

I used to be a little bit nervous when using hashes, so I asked all of my study partners to give me problems with hashes when solving live coding challenges. That took away my fear pretty quickly, and I was happy to see some muscle memory from those practice sessions kick in today.

The problem was a fun one, presumably close to something you might see in real life where you have two different sets of data you have to compare and consolidate. Here is the problem: Help a bookseller!

Here was my first version, using arrays. Pardon the weird parameter names and method name – I used the provided names, not too happy about how weird the provided names are.

#Version 1
def stockList(list_of_art, list_of_cat)
  return '' if list_of_art == '' || list_of_cat == ''

  list_of_cat.map do |c|
    sum = 0

    list_of_art.each do |a|
      if a.start_with?(c)
        sum += a.chars.select { |i| i if ('0'..'9').include?(i) }.join.to_i
      end
    end
    
    "(#{c} : #{sum})"
  end.join(' - ')

end

And my second solution, using a hash object. I also let myself look at the documents to find a method that I had forgotten the name of (#scan), and I used Rubular to test out my little regex argument. Based on the fact that I failed the test attempts from my first solution, I figured out that I needed to return an empty string if none of the data from the first set matched up to the second set.

# Version 2
def stockList(list_of_art, list_of_cat)
  return '' if list_of_art == '' || list_of_cat == ''
  results = {}

  list_of_cat.each do |c|
    results[c] = 0
    list_of_art.each { |a| results[c] += a.scan(/\d/).join.to_i if a.start_with?(c) }
  end
  
  return '' if results.values.sum == 0
  results.map { |k, v| "(#{k} : #{v})" }.join(' - ')
end