Dobs Totev
Dobs Totev

Reputation: 17

How to perform a sum operation with the values of an Array until it reaches a certain number in Swift?

So I have the following

class Passenger {

    let passengerId: Int, firstName: String, lastName: String, daysOnTrip: Int

    init(passengerId: Int, firstName: String, lastName: String, daysOnTrip: Int) {
        self.passengerId = passengerId
        self.firstName = firstName
        self.lastName = lastName
        self.daysOnTrip = daysOnTrip
    }

}

let peopleTravelling = [
    Passenger(passengerId:1, firstName:"John", lastName:"Doe", daysOnTrip: 10),
    Passenger(passengerId:2, firstName:"Seb", lastName:"Johns", daysOnTrip: 5),
    Passenger(passengerId:3, firstName:"Emilia", lastName:"Clarke", daysOnTrip: 7)
]

singleDayCosts:[Double] = [3.3333333333333335, 3.3333333333333335, 3.3333333333333335, 3.3333333333333335, 3.3333333333333335, 5.0, 5.0, 10.0, 10.0, 10.0]
let mappedDays = peopleTravelling.map{$0.daysOnTrip}
var tripCostsPerson: [Double] = []

I am trying to fill the array tripCostsPerson: [Double] = [] with the SUM of the first "X" number of values from SingleDayCosts where "X" is = to the number of daysOnTripinside the peopelTravelling.

e.g. For Passenger 1 should be the sum of all 10 values in singleDayCosts:[Double] For Passenger 2 should be the sum of the first 5 values in singleDayCosts:[Double] For Passenger 3 should be the sum of the first 7 values in singleDayCosts:[Double]

I tried with this code

for daysSpend in peopleTravelling {
    tripCostsPerson.append(singleDayCosts.reduce(0, +))
}

But for all 3 passengers, I get the Sum of all 10 numbers - [56.66666666666667, 56.66666666666667, 56.66666666666667]

How to restrict the operation in the loop to stop adding values from the singleDayCosts array depending on the number inside daysOnTrip. Any thoughts?

Upvotes: 0

Views: 80

Answers (1)

Sandeep
Sandeep

Reputation: 21154

You can use prefix method.

for person in peopleTravelling {
    let sumOfCosts = singleDayCosts.prefix(person.daysOnTrip).reduce(0, +)
    tripCostsPerson.append(sumOfCosts)
}

A bit more functional approach here.

let tripCostsPerson = peopleTravelling.map { person in
    singleDayCosts.prefix(person.daysOnTrip).reduce(0, +)
}

Upvotes: 2

Related Questions