# Enigmatic Code

Programming Enigma Puzzles

From New Scientist #2697, 28th February 2009 [link]

Harey and Tortus decided to race from Harey’s house to school, a distance of a whole number of metres. They each ran at their own steady speed and when Harey reached school, Tortus was over half way there, but still had a two-figure number of metres to go.

The next day they repeated the race, but this time Harey decided to give Tortus a head start equal to the winning margin of the previous day. So Harey walked that number of metres away from his house in the opposite direction to school before the race started. Once again, Harey got to school first, ahead by a two-figure number of metres. The second winning margin had the same pair of digits as the first, but in reverse order.

How far is it from Harey’s house to the school?

[enigma1534]

### 2 responses to “Enigma 1534: Head start”

1. Jim Randell 1 July 2012 at 7:32 pm

Here’s my original Perl solution. It runs in 14ms.

```use strict;

my (\$A, \$B, \$D1, \$D2, \$d);

for \$A (1..8) {
for \$B (\$A+1..9) {
\$D1 = int("\$B\$A");
\$D2 = int("\$A\$B");

# distance to the school is...
\$d = \$D1 * \$D1 / \$D2;

# the tortoise should have got more than half way
next unless \$D1 * 2 < \$d;

# and it should be an integer
next unless abs(int(\$d + 0.1) - \$d) < 0.0001;

printf "D1=%s > D2=%s : d=%s t=%s\n", \$D1, \$D2, \$d, \$d - \$D1;
}
}
```

Solution: The distance from Harey’s house to the school is 192 m.

• Jim Randell 1 July 2012 at 7:35 pm

And here’s a Python solution (along with the analysis to give the equation for the required distance). It runs in 40ms.

```from enigma import irange, printf

# suppose Harey's house is a distance d from the school
# and that Harey travels at speed h and Tortus at speed t

# then on the first day, in time t1:
# t1 = d / h and t1 = (d - ab) / t
# where ab is the two digit distance remaining for Tortus
# hence: t / h = (d - ab) / d  [1]

# on the second day, in time t2:
# t2 = (d + ab) / h and t2 = (d - ba) / t
# where ba is the two digit distance remaining for Tortus
# (the reverse of the previous days digits)
# hence: t / h = (d - ba) / (d + ab)  [2]
# and: ba < ab

# equating [1] and [2] gives:
# (d - ab)(d + ab) = d(d - ba)
# => d^2 - (ab)^2 = d^2 - d.ba
# => d = (ab)^2 / ba

# and d is a whole number < 2 * ab

for b in irange(1, 8):
for a in irange(b + 1, 9):
(ab, ba) = (10 * a + b, 10 * b + a)

(d, r) = divmod(ab * ab, ba)
if r > 0 or d < 2 * ab: continue

printf("d={d} [ab={ab} ba={ba}]")
```