# Enigmatic Code

Programming Enigma Puzzles

## Enigma 1224: Age-changing

From New Scientist #2380, 1st February 2003 [link]

If you start with my age, in years, and apply the four operations: in some order, then the final answer you get is my husband’s age in years.

Funnily enough, if you start with his age and apply the same four operations in a different order, then you get my age.

What are our two ages?

[enigma1224]

### 2 responses to “Enigma 1224: Age-changing”

1. Jim Randell 20 June 2015 at 8:11 am

I assumed the couples ages were between 16 and 112.

This Python program runs in 50ms.

```from itertools import permutations
from collections import defaultdict
from enigma import irange, printf

# the operations
def op1(x):
return x + 2

def op2(x):
(d, r) = divmod(x, 8)
assert r == 0
return d

def op3(x):
return x - 3

def op4(x):
return x * 7

ops = (op1, op2, op3, op4)

label = { op1: '+2', op2: '/8', op3: '-3', op4: '*7' }

# apply the functions in fns to x
def compose(x, fns):
for fn in fns:
x = fn(x)
return x

# look for ages is the range 16 - 110
d = defaultdict(list)
for age1 in irange(16, 110):
# consider possible orders of operations
for s in permutations(ops):
# map age1 -> age2
try:
age2 = compose(age1, s)
except AssertionError:
continue

if not(age2 < 16 or age2 > 110):
d[age1].append((s, age2))

# look for two ages
for (A, Bs) in d.items():
for (s1, B) in Bs:
if B < A: continue
if B not in d: continue
for (s2, A2) in d[B]:
if A == A2 and s1 != s2:
printf("{s1} x {A} = {B}, {s2} x {B} = {A}", s1=tuple(label[f] for f in s1), s2=tuple(label[f] for f in s2))
```

Solution: The couple are aged 48 and 53 (although we don’t know which age applies to the husband and which to the setter).

The transitions between the two ages are given below:

48 ÷ 8 = 6; 6 + 2 = 8; 8 × 7 = 56; 56 – 3 = 53
53 × 7 = 371; 371 – 3 = 368; 368 ÷ 8 = 46; 46 + 2 = 48

In the published solution it gives the setters ages as 48 and the husbands age as 53, but I don’t see any way to distinguish the ages.

2. hakank 22 June 2015 at 9:37 am

Here are two other, and different, approaches:

1) Constraint Programming with MiniZinc: http://hakank.org/minizinc/age_changing.mzn
Note: Just few FlatZinc solvers can handle mixed var int and var floats: Gecode, JaCoP, and G12 mip. Gecode solves this in 23ms (and with symmetry breaking that “my age” <="husbands age": 5ms).

2) Picat: http://hakank.org/picat/age_changing.pi
Two variants: go/0 use string parsing and go2/0 use functional + logic approach. However, both models use non-deterministic predicate such as between/3, permute/2.
Solve time is around 200ms.

This site uses Akismet to reduce spam. Learn how your comment data is processed.