loading...

Daily Challenge #234 - Happy Birthday!

thepracticaldev profile image dev.to staff ・1 min read

It can be really uncomfortable to talk about your age when you get older. Sometimes you just want to be twenty again! Well, with some math magic that's totally possible - just select the correct number base. For example, if they are turning 32, that's 20 in base 16!

Translate the given age to the desired 20 or 21 years, and indicate the number base, in the format specified below.

Note: input will be always > 21

Examples:
32 --> "20, in base 16"
39 --> "21, in base 19"

Tests:
a, b; where a is the age of the person, b is the desired age.
50, 20
50, 21
43, 20
66, 21


This 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

markdown guide
 

Here is the Python solution:

def womens_age(n):
    str_format = "%s? That's just %s, in base %s!"

    base = int(n / 2)
    age = 21
    if n % 2 == 0:
        age = 20


    return str_format %(n, age, base)
 

Are fractional bases allowed? Or should the function return something special for impossible situations.

Many of the tests are impossible with integral bases. For example, to write 50 as 21 in base n, 2n + 1 = 50, and there is no integer solution because 50 is even.

 
const solution = (age, desiredAge) => {
    if(age > 21 && (desiredAge === 20 || desiredAge === 21) && age % 2 === desiredAge % 2) {
        return `${desiredAge}, in base ${~~(age/2)}`
    }
    return `Impossible`
}

 

This function checks if given age can be translated to the given required age,

# checks if age can be translated to 20 or 21
def isPossible(age : int, changedAge : int) -> bool:
    return age > 21 and age%2 == changedAge%2


print(isPossible(50, 20)) # output -> True
print(isPossible(50, 21)) # output -> False
print(isPossible(43, 20)) # output -> False
print(isPossible(66, 21)) # output -> False

This function returns the translated age and the base if possible,

# translates given age to 20 or 21 and prints the base
def translateAge(age : int):
    if(age > 21):
        return str(20 + age%2) + ", in base " + str(age//2)
    return "Not possible to translate"


print(translateAge(39)) # output -> 21, in base 19
print(translateAge(32)) # output -> 20, in base 16
print(translateAge(50)) # output -> 20, in base 25
print(translateAge(20)) # output -> Not possible to translate