Hey guys, Leo here.

Today we’ll continue the series Algorithms, the Final Frontier. Always remember folks, this is ONE of many possible solutions for the problem. The challenge is here: The Challenge

Let’s go!

The problem: Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. E.G. update inventory([[21, “Bowling Ball”], [2, “Dirty Sock”], [1, “Hair Pin”], [5, “Microphone”]], [[2, “Hair Pin”], [3, “Half-Eaten Apple”], [67, “Bowling Ball”], [7, “Toothpaste”]]) should return an array with a length of 6. Solution: I divide this problem into two parts:

  1. Create a compiled inventory
  2. Sort the compiled inventory

For the first part, you can just create a dictionary for that like:  

var a1 = [[2,"cafe"],[8,"water"],[2,"bola"],[2,"futebolball"],[2,"solarium"],[2,"pool"]]
var a2 = [[8,"cafe"],[3,"water"],[2,"futebolball"],[2,"solarium"],[2,"pool"]]

var dict : [String:Int] = [:]

a1.append(contentsOf: a2)


for row in a1 {
    let itemNumber = row[0] as! Int
    let itemName = row[1] as! String
    if dict[itemName] != nil {
        dict[itemName] = dict[itemName]! + itemNumber
    } else {
        dict[itemName] = itemNumber
    }
}

and for the second part just a little FP here:  

print(dict.lazy.sorted { a1, a2 -> Bool in
    a1.key < a2.key
}.map { itemName, value -> [Any] in
    [value,itemName]
})

 

Continue Algorithm Studying

If you like the solution for this inventory problem, you will probably like the “special palindrome problem”. There we use a two-pointer technique to traverse the array simultaneously from both sides.

Functional programming is a good technique to be familiar in algorithms because you can leverage your code using premade functions. For example in this solution for a “shopping cart” problem we use two functional operations to solve the whole problem.

 

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or just leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for reading and… That’s all folks.

Image Credit: Wikiart