In this post we can solve exercise problem "Apple and Orange" in which we should print the number of apples and oranges that land on Sam's house.
Read complete challenge detail from hackerrank.com
Full Swift Solution is given below:
func countApplesAndOranges(s: Int, t: Int, a: Int, b: Int, apples: [Int], oranges: [Int]) -> Void {
// 1
let applesDistance = apples.map( { $0 + a })
var totalAppleOk = 0
applesDistance.forEach({ ad in
// 2
if (s...t).contains(ad) {
totalAppleOk = totalAppleOk + 1
}
})
print("\(totalAppleOk)") // prints number of Apples
let orangeDistance = oranges.map( { $0 + b })
var totalOrangeOk = 0
orangeDistance.forEach({ od in
if (s...t).contains(od) {
totalOrangeOk = totalOrangeOk + 1
}
})
print("\(totalOrangeOk)") // prints number of Oranges
}
countApplesAndOranges(s: 7, t: 11, a: 5, b: 15, apples: [-2, 2, 1], oranges: [5, -6]) // prints 1 \n 1
1. Add 'd' units for each fallen apples i.e each distance between Apple tree 'a' and Starting point 's'.
2. For each distances 'd' of apples, check whether it is under valid area range. If so, increment apple count & print the count.
Repeat the same logic for Orange case as well. Do you have better solution ? Let us know in the comments. Thanks for reading and Happy coding.