Problem: The product of the ages of David's children is the square of the sum of their ages. David has less than eight children. None of his children have the same age. None of his children is more than 14 years old. All of his children is at least two years old. How many children does David have, and what are their ages?
Answer:
(12,6,4,2)
Solution:
showA way to mathematically analyze this problem is to write the general form of equations, differentiate and maximize w.r.t to largest age. That leads to a Fibonacci number series. But after that complex heuristics have to be employed to devise the solution (and we cannot guarantee if that is the unique).
This is a constraint satisfaction problem. The best way to solve it is write the code. The following code solves the problem in general sense:
Function find_ages(kidAges)
s = sum(kidAges)
p = product(kidAges)
if s*s == p
print kidAges
l = length(kidAges)
if l >= 7
return
else if l == 0
x = 14
else
x = kidAges[l]
end
for i = 2 to x-1
kidAges1 = clone(kidAges)
kidAges1.add(i)
find_ages(kidAges1)
end
end
// call
find_ages([])
After running the code, we see the following solution
[12, 6, 4, 2]
Note that in the above pseudo code, we cloned the kidAges array. If we dont clone then it wont work properly. Down side of cloning is that now we use a huge amount of memory. How do we write code without cloning? Check the python script attached below.
Source Code:
david_kids_ages.py
Can you post a solution to this problem ?
ReplyDeleteIs there a solution other than evaluating all possible combinations from 2 to 14 ?
This comment has been removed by the author.
ReplyDeleteEDIT: tried to correct indentation.
ReplyDelete"... None of his children have the same age". This has not been checked for in your solution.
Here's the solution:
import itertools;
from operator import mul;
def solveage():
a = xrange(2,8);
b = xrange(1,14);
for i in a:
agelist = xrange(1,14);
combos = itertools.combinations(agelist, i);
for combi in combos:
rhs = pow(sum(combi),2);
lhs = reduce(mul, combi)
if lhs==rhs:
print combi;
result:
(2, 4, 6, 12)
(1, 2, 4, 8, 9)
Thanks divine for pointing it out. Updated the code. The change was instead of x in for loop, we have x-1
ReplyDelete