Reputation: 19504
totalDirection = 1540m
1st KM = $10
2nd KM = $8
Others(normal) KM = $5
how do I calculate this logic? Users should pay $10 for 1st km, then 2ns km for $8 and for others $5.
model.startUpCharge
is array, store 10$ and $8
/// [totalDistance] is in meters
double calculateTripPrice(RideModel model, double totalDistance) {
double totalPrice = 0;
double standardPrice = 0;
totalPrice = model.normalCharge *
((totalDistance / 1000) - model.startUpCharge.length);
for (var i = 0; i < model.startUpCharge.length; i++) {
standardPrice = standardPrice + model.startUpCharge[i];
}
totalPrice = totalPrice + standardPrice;
return totalPrice;
}
1540m logic = 1000m pay $10 and 540m pay $8
@creativecreatorormaybenot answer
the answer should be 50, but result is 5.
The problem is: If I add 1 meter, the price should be 50. 1st KM has an initial charge. not change
import 'dart:math' as math;
class RideModel{
final List startUpCharge;
final double normalCharge;
RideModel({this.startUpCharge,this.normalCharge});
}
main() {
calculateTripPrice(RideModel(startUpCharge: [50,51],normalCharge: 10),1);
}
double calculateTripPrice(RideModel model, double totalDistance) {
var remainingDistance = totalDistance, price = .0;
// Kilometers with special charge
for (var i = 0; i < model.startUpCharge.length; i++) {
price += model.startUpCharge[i] / 1000 * math.min(1000, remainingDistance);
remainingDistance -= math.min(1000, remainingDistance);
}
// Remaining kilometers
price += model.normalCharge / 1000 * remainingDistance;
remainingDistance = 0;
print(price);
return price;
}
Upvotes: 0
Views: 83
Reputation: 126854
You can simply iteratively add to your price and subtract from the distance. Based on that, there will only be added to the price when there is still remaining distance and the correct factor is used every time.
double calculateTripPrice(RideModel model, double totalDistance) {
var remainingDistance = totalDistance, price = .0;
// Kilometers with special charge
for (var i = 0; i < model.startUpCharge.length; i++) {
price += model.startUpCharge[i] / 1000 * math.min(1000, remainingDistance);
remainingDistance -= math.min(1000, remainingDistance);
}
// Remaining kilometers
price += 5 / 1000 * remainingDistance;
remainingDistance = 0;
return price;
}
Remember to import 'dart:math' as math;
.
Upvotes: 1