Search code examples
javacomputationoff-by-one

Age computation always off by one


The task is to create a function.

The function takes two arguments:

  • current father's age (years)
  • current age of his son (years)

Сalculate how many years ago the father was twice as old as his son (or in how many years he will be twice as old).

public static int TwiceAsOld(int dadYears, int sonYears){

    int dadYearsTemp = dadYears;
    int years = 0;
    int yearsAgo = 0;

    for (int i = 0; i <= dadYears; i++ ){
        if (dadYearsTemp / 2 == sonYears) {
            years = dadYearsTemp;
            yearsAgo = dadYears - years;
            System.out.println(yearsAgo);
            return yearsAgo;
        }
        else if (sonYears * 2 > dadYears) {
            years = (sonYears * 2) - dadYears;
            System.out.println(years);
            return years;
        }
        dadYearsTemp = dadYearsTemp -1;
    }

    return 42; // The meaning of life

}

For example, with an input of (30, 7) I would expect my function to return 16, because 16 years ago the father was 14, which means he was twice as old as his son now (7). But my function returns 15.

I guess it's not a big mistake but I honestly can't find out why it doesnt work, so I would apreciate some help.


Solution

  • Let father's current age = f

    son's current age = s

    let x years back, father was twice as old as son.

    then 2(s-x) = (f-x) => x = 2*s - f

    Note: if x comes negative, then after x years , father will be twice as old as son(test for input[25,5])

    public static void main(String[] args) {
        int x = twiceAsOld(25, 5);
        System.out.println(x);
      }
    
      public static int twiceAsOld(int dadYears, int sonYears) {
        return 2*sonYears - dadYears;
    
      }