0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

My programme returned me: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 3, 3, 3, 3, 2, 2, 1, 1, 1] :/ Not sure why the first 1 to 10 are showing in the array?
Ops no worries I fixed it thanks for the assitsance

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.