Dobs Totev
Dobs Totev

Reputation: 17

Comparing values from two different arrays in Swift

So I am having this defined

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)
]

var tripDuration:Int
var tripCost:Double
var tripCostPerDay:Double

tripCost = 100.00
tripDuration = 10
tripCostPerDay = tripCost / Double(tripDuration)

What I am trying to find out is in each day of tripDuration, how many passengers are present based on daysOnTrip.

So I was thinking to add each day of the tripDuration into an array like this

var daysOfTrip: [Int] = []

for day in 0...tripDuration-1 {
    daysOfTrip.append(day)
}

And then I got stuck with how to find out for each day how many passengers there are available. I was thinking to somehow compare the day of the trip vs. the daysOnTrip from peopleTravelling.

e.g. Day 1: 1<=10 && 1<=5 && 1<=7 => 3 passengers are present ... Day 7: 7<=10 && 7<=5(not true) && 7<=10 => 2 passengers are present

But maybe my logic is off. Any advice?

Upvotes: 0

Views: 48

Answers (1)

vadian
vadian

Reputation: 285069

First of all map peopleTravelling to an array of the daysOnTrip values.

let daysArray = peopleTravelling.map{$0.daysOnTrip}

Then filter the array by the condition is the value equal or greater than day and count the occurrences

var daysOfTrip = [Int]()

for day in 1...tripDuration {
    daysOfTrip.append(daysArray.filter{$0 >= day}.count)
}

or swiftier

let daysOfTrip = (1...tripDuration).map{ day in
    daysArray.filter{$0 >= day}.count
}

The result is [3, 3, 3, 3, 3, 2, 2, 1, 1, 1]

Be careful with the indices. The day in the loop starts with one but the result array starts with zero.

Upvotes: 1

Related Questions