-1

I have an array that describes a list of auto parts (Swift/IOS,array already in such structure arrived from other source.):

let parts = [
    "Wheel = 230$",
    "Door = 200$",
    "Wheel = 300$",
    "Seat = 150$",
    "Seat = 150$",
    "Rugs = 100$"]

I need to calculate the sum of the prices of the auto parts for each type of part. Here's the result I'm looking for:

let expectedResult = [
    "wheel 530$",
    "Door 200$",
    "Seat 300$",
    "Rugs 100$"
]

I don’t understand how to do it.

9
  • 3
    Checksum? Btw you have fancy quotes in your second code block, you should replace with ". Commented Aug 4, 2021 at 20:31
  • 2
    This code doesn’t even compile. And what does checksum mean? Commented Aug 4, 2021 at 20:32
  • 1
    Could you add more details? What kind of checksum are you looking for, exactly? Commented Aug 4, 2021 at 20:34
  • 1
    Use a custom type instead of strings that must be parsed. Looks like OP wants to sum the amounts for each item, for instance there are two “Seat” so the sum is 300 for that item Commented Aug 4, 2021 at 20:36
  • 1
    Also: don't use the leading comma style in Swift. It was invented in SQL as a workaround for its terrbile syntax, and the way it explodes when having excess commas. Swift ignores an excess trailing comma, so it doesn't have that issue, thus no need for that gross workaround. Commented Aug 4, 2021 at 20:36

1 Answer 1

0

Here is a solution where I loop through the array and split each element on "=" and then sum the values together using a dictionary. Once that is done the dictionary is converted back to an array

let parts = [
    "Wheel = 230$",
    "Door = 200$",
    "Wheel = 300$",
    "Seat = 150$",
    "Seat = 150$",
    "Rugs = 100$"]

var values = [String: Int]() // Used to calculate totals per part

parts.forEach { string in
    let split = string.split(separator: "=")

    // Make sure the split worked as expected and that we have an integer value after the =
    guard split.count == 2,
          let value = Int(String(split[1]).trimmingCharacters(in: .whitespaces).dropLast()) else { return }

    let key = String(split[0]).trimmingCharacters(in: .whitespaces)

    // Sum values over the part name
    values[key, default: 0] += value
}

// Convert back to an array of strings
let output = values.map { "\($0.key) \($0.value)$"}

print(output)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! This is a very elegant solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.