loading...

Daily Challenge #106 - Average Fuel Consumption

thepracticaldev profile image dev.to staff ・1 min read

You've just returned from a road trip and are curious about your car's fuel consumption during the trip. Unfortunately, you didn't reset the counter before leaving home. You do know the average consumption of your car and the previous distance you have traveled in that vehicle.

Write a function that takes two pairs of input (before, after) and returns the calculated average fuel consumption of your car during your trip, rounded to the first decimal place.

Both pairs consist of two valid numbers:

  • average fuel consumption of the car (l/100km, float)
  • previous distance traveled (km, integer)
Example:
      BEFORE                   AFTER                  DURING
avg. cons, distance     avg. cons, distance         avg. cons
[l/100km]    [km]       [l/100km]    [km]           [l/100km]
[   7.9  ,   100  ]  ,  [   7.0  ,   200  ]    -->     6.1
[   7.9  ,   500  ]  ,  [   7.0  ,   600  ]    -->     2.5
[   7.9  ,   100  ]  ,  [   7.0  ,   600  ]    -->     6.8

Have fun coding!


Today's challenge comes from Anter69 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Posted on by:

thepracticaldev profile

dev.to staff

@thepracticaldev

The hardworking team behind dev.to ❤️

Discussion

pic
Editor guide
 

Ruby:

# frozen_string_literal: true

require 'json'
# Save file as fuel.rb and then run `ruby fuel.rb [7.9,100] [7.0,600]`
class FuelConsumption
  def initialize(before, after)
    @before = JSON.parse(before)
    @after = JSON.parse(after)
  end

  def calculate
    trip = @after[1] - @before[1]
    puts(
      ((consumed(@after) - consumed(@before)) / trip).round(1)
    )
  end

  def consumed(data)
    data[1] * data[0]
  end
end

FuelConsumption.new(*ARGV).calculate
 

typescript

interface Reading {
  centilitersPerKilometer: number;
  km: number;
}

const roundToPlaces = (places: number, value: number) =>
  +(Math.round(((value + `e+${places}`) as unknown) as number) + `e-${places}`);

const avgFuelConsumption = (start: Reading, end: Reading) => {
  const beforeConsumptionInCentiliters =
    start.km * start.centilitersPerKilometer;

  const afterConsumptionInCentiliters = end.km * end.centilitersPerKilometer;

  const consumptionInCentiliters =
    afterConsumptionInCentiliters - beforeConsumptionInCentiliters;

  const distanceInKilometers = end.km - start.km;

  const centilitersPerKilometer =
    consumptionInCentiliters / distanceInKilometers;

  return roundToPlaces(1, centilitersPerKilometer);
};
 

Haskell

average :: Float -> Float -> Float -> Float -> Float
average x1 x2 y1 y2 =
    (fromIntegral $ round $ (y1 * y2 - x1 * x2) * 100 / (y2 - x2) / 100 * 10) / 10

main :: IO ()
main = do
    print $ average 7.9 100 7 200 -- 6.1
    print $ average 7.9 500 7 600 -- 2.5
    print $ average 7.9 100 7 600 -- 6.8

Playground

Hosted on Repl.it.

 

the code is self-explanatory

def avg_fuel_consumption(before, after):
avg_bef = before[0] * (before[1] / 100)
avg_aft = after[0] * (after[1] / 100)
avg_current = avg_aft - avg_bef
print("The average fuel consumption during hte trip is :", avg_current)

def worker_method():
before = []
after = []

before.append(float(input("Enter the average consumption before trip: ")))
before.append(int(input("Enter the distance travelled  before trip: ")))
after.append(float(input("Enter the average consumption after trip: ")))
after.append(int(input("Enter the distance travelled  after trip: ")))

return (avg_fuel_consumption(before,after))

if name == 'main':
worker_method()
while True:
answer = input("Would you like to try again? Y/N: ").lower()
if answer == 'y':
worker_method()
elif answer == 'n':
break
else:
answer = raw_input('Incorrect option. Type "YES" to try again or "NO" to leave": ').lower()

 

Extra credit: Convert from l/100km to SI units and visualize the resulting quantity.

 

So like in Kg? I'm not sure I understood the principle behind the SI units. Could you bring some light to it?