Train Maths

Background

  • A game played in Sydney trains by bored schoolkids.
  • Every train carriage has a four-digit number.
  • Use the digits to make ten using plus, minus, multiply and divide.

Extra Rules

  • Using the numbers in order scores higher.
  • Brackets are involved
  • Some people use other math operations like exponents, roots etc.

My version only finds one solution

There can be many

Examples

thumb-pict0032-3
thumb-pict0032-4
thumb-pict0032-5
thumb-pict0032-6

Programming task:

In-order search:

  • given four digits
  • run through a sequence of calculations with those digits
  • stop when you get to one which calculates to 10

Programming task:

Any-order-search:

  • given four digits
  • for each permutation of those digits
    • run through a sequence of calculations with those digits
    • stop when you get to one which calculates to 10

So, lots of calculations…

Some permutations are identical so you can optimise those away

If any of the digits are repeated, some permutations will be identical

1234 has 24 permutations

1231 also has 24 permutations, but some of them are identical, so there are really only 12

So how does the website calculate the answer?

It doesn't

There are less than 1,000 answers, so it's easiest to precompute them and look them up.

I used Perl modules to pre-calculate all the answers:

Algorithm::Permute

Algorithm::Combinatorics

Because permutations and combinations are different things.

This script runs it through 768 different eval() calls:

Screenshot

The strings for those eval() calls were in turn generated by this script:

Screenshot

To create this library of possible combinations:

Screenshot

So what is the javascript doing while it 'finds' the answer?

Nothing!

It's just a better user experience if you feel like the website is really working hard finding your answer…

Questions?

/