ruby-on-rails - Fare calculator for any entity
问题描述
I'm working on creating a booking fare calculator.
There are 28
bus stations,
Base Price is 100
up to 5
bus stations.
Later 50
extra for every 5
bus stations.
Single trip from 1 to 28
is 300
.
Here is my solution,
BASE = 100
stops = (start - end).abs
case stops
when 1..5
BASE
when 5..10
BASE + 5
when 10..15
BASE + 10
when 15..16
BASE + 15
when (station_array.length - 1)..station_array.length
200
end
I was looking for a good optimised and scalable solution. Suppose if, we add new stations, the fare logic should require minimal changes.
解决方案
您应该能够只用基本的数学来做到这一点,这可以作为您构建的示例。
以后每 5 个公交车站加收 50 元。
这有点不清楚,是在5个额外站之后计算的额外票价还是已经在第一个额外的?
例如是吗?
A: 6 stations = BASE_FARE + EXTRA_FARE
# or...
B: 6 stations = BASE_FARE only
ceil
如果您只想计算5个站后的额外票价,您可以删除该方法,我这里的方法是1-4个额外的车站已经添加了额外的票价。
至于往返,您可以添加一个额外的检查来查看站数 = total_stations
TOTAL_STATIONS = 500
ROUNDFARE = 300 # or whatever
BASE_PRICE = 100
BASE_STATIONS = 5
EXTRA_PRICE = 50
EXTRA_STATIONS = 5
def calc_price(stations)
return ROUNDFARE if stations = TOTAL_STATIONS
total_price = base_price
# Substract the 5 base stations
stations -= BASE_STATIONS
# Add 50 for every 5 stations
# to_f is used so it does float division
# ceil is used to round up, e.g. 3 / 5 => 1
total_price += (stops / EXTRA_STATIONS.to_f).ceil * EXTRA_PRICE
total_price
end