The problem is as follows:
Dick is d=12 years old. When we say this, we mean that it is at least twelve and not yet thirteen years since Dick was born.
Dick and Jane have three pets: Spot the dog, Puff the Cat, and Yertle the Turtle. Spot was s years old when Puff was born; Puff was p years old when Yertle was born; Spot was yy years old when Yertle was born. The sum of Spot’s age, Puff’s age, and Yertle’s age equals the sum of Dick’s age (d) and Jane’s age (j). How old are Spot, Puff, and Yertle?
The input's given are s,p,y,j and the output required is: spot's age, puff's age and yertle's age.
My solution was as follows:
import sys
import math
d = 12
for line in sys.stdin:
line = [int(x) for x in line.strip("\n").split()]
s = line[0]
p = line[1]
y = line[2]
j = line[3]
yertle = (d+j-y-p)/3.0
difference = yertle - math.floor(yertle)
if difference > 0.5:
# for the 0.66666 cases
spot = puff = int(math.ceil(yertle+p))
yertle = int(math.floor(yertle))
else:
# for the 0.33333 cases
yertle = int(math.floor(yertle))
puff = yertle + p
spot = d+j - puff - yertle
print spot,puff,yertle
but it is incorrect on certain inputs such as: s=5, p=5, y=10, j=10. Because for those specifications the actual age's of the dogs are: spot=12.333, puff=7.333, yertle=2.333 but because we are doing integer division we get 12,7,2 instead. However, those results don't satisfy the $$spot + puff + yertle = dick + jane$$ rule. Does anyone have other ideas on where I am making a mistake or how i should've approached/solved this?
Don't use float arithmetics, work with integers.
Let's denote D+J = DJ
, Spot's age S
, Puff's age P
, Yertle's age Y
Let's Spot birthday time is zero, so Puff was born in interval [s, s+1)
, Yertle was born in interval [y, y+1)
. Current time is in interval [S, S+1)
.
If we look onto time line, we can see that
S = y + Y
or
S = y + Y + 1
and
S = s + P
or
S = s + P + 1
age sum is
DJ = S + Y + P = S + S - y + S - s - (0, 1, 2)
where (0,1,2) is possible addendum
3 * S = DJ + y + s + (0,1,2)
We can see that right part must be divisible by 3, so next calulations depends on value
M = (DJ + y + s) modulo 3
case M = 0: (5 5 10 9)
S = (DJ + y + s) / 3 = (21 + 15) / 3 = 12
P = S - s = 12 - 5 = 7
Y = S - y = 12 - 10 = 2
case M = 1: (5 5 10 10)
here we should add 2 to make sum 37 divisible by 3
S = (DJ + y + s + 2) / 3 = (22 + 15 + 2) / 3 = 13
P = S - s - 1 = 13 - 5 = 1 = 7
Y = S - y - 1 = 13 - 10 - 1 = 2
now more complex case M = 2 (5 5 11 10):
here we should add 1 to make sum 38 divisible by 3
and solve - where use 1 - for P or for Y calculation?
We can determine this evaluating s/p/y relation:
if y = s + p + 1 then use 1 for Puff's age else for Yertle
(because Puff's fraction is larger then Yertle's fraction,
she was born in the later year period)
here 11 = 5 + 5 + 1, so
S = (22 + 16 + 1) / 3 = 13
Y = S - y = 13 - 11 = 2
P = S - s - 1 = 13 - 5 - 1 = 7