Search code examples
swift

How To Convert Car km/miles in to km by Year?


everybody.

I got logic problem with car odometer, i don't understand how to devide a car age in km by year.

For example i got car with 2015 year and 250 000 km in odometer.

it's ok, if i just minus current year with registration year i got car age then i just deviding a car age in odometer or odo in age depending on numbers. then i got a car km route by year. but what if i want get age of car with 1920 year and 1 km of full route. or car with last year.

it does not show me a current data, in example below

    func getOdoByYear(registration: Int, currentYear: Int, currentODO: Int) -> Int {
        
        
        if  currentODO == 0 || currentYear == registration {
        
            return currentODO
        }
        
        var carAge = currentYear - registration
        
        if carAge >= currentODO {
            return carAge /  currentODO
        } else {
            return currentODO / carAge
        }
    }

if car registered year before i got a one year of age of car, and if a car route is only 1 km it also cant be calculated from 1920 for example.


Solution

  • In order to calculate the average of kilometers traveled in a year by a car, you should just divide the km traveled by the age of the car.

    Example, given:

    • current year: 2024
    • year of registration: 1920
    • total km traveled (ODO): 7 km

    the average of km traveled in a year is calculated by:

    7 km / (2024 - 1920) ~ 67.31 m/year
    

    Code example:

    func getOdoByYear(registration: Int, currentYear: Int, currentODO: Int) -> Double {
        // TODO: check parameters, i.e. currentYear > registration, currentODO >= 0
        var carAge = currentYear - registration
        var average:Double = Double(currentODO) / Double(carAge)
        return average
    }
    

    you also should handle the case registration == currentYear, otherwise you get a division by zero. This is up to you: you can just return the currentODO (even the first year is not completed yet) or throw an error because it might not make sense at all.