Leonardo Maia Pugliese
Holy Swift

Holy Swift

Inventory Update Problem in Swift

Leonardo Maia Pugliese's photo
Leonardo Maia Pugliese

Published on Apr 30, 2020

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Hey guys Leo here,

Today we'll continue the series Algorithms, the Final Frontier. Always remember folks, this is ONE of many possible solution 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. updateInventory([[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 in 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]
})

That's all folks!

That's all my people, I hope you liked as I enjoyed write this article. 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 writing freelancing! Just reach me in LinkedIn or Twitter for details.

Thanks for the reading and... That's all folks.

Did you find this article valuable?

Support Leonardo Maia Pugliese by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this