Solving seemingly simple math problems using Perl

5x5 Test Run

The sought-after groups in the math puzzle can now be put together very easily from this megasquare in a way that avoids overlap between participants on several consecutive days. Because these are only 5x5 squares, the method can only generate five groups each with four (n-1) participants for five days: one teacher (of a total of five), one male student (also of five) and two female students (out of 10). Figure 7 shows the result, which is practically just a simple transformation of the entries from the megasquare in Figure 6.

Figure 7: Groups made up of one teacher, one male student and two female students from four 5x5 MOLS.

The script in Listing 1 [5] moves from left to right and from top to bottom through the entries and translates them into people. The entry 1111 thus becomes i1 b1 g1 g6, because it relates to the first teacher, the first boy, the first girl from the first group, and the first girl from the second group. The entry 3524 accordingly becomes i3 b5 g2 g9, and so on.

Listing 1

combi-prime

 

That's How to Do It

But, how does the script initially generate the four orthogonally arranged Latin squares from which the group arrangement can then be easily derived? The process is pretty simple, as it concerns 5x5 squares and five is a prime number.

Trust Is Good

The x and y values printed in black along the edges of the squares in Figure 5 run from 0 to 4 and are in mixed-up order (0,2,3,4,1), because order does not matter to the algorithm. Each element of the matrix is computed by the simple formula (ay+x) mod 5+1, where a is set to 1 for the first square, to 2 for the second, and so on.

This process results in the following value for the element that is in the second column of the third row of the fourth square: The y value of the third row of the fourth square is 3, the x value of the second column is 2, and the value for a in the fourth square is 4, this returns 4x3+2=14. Reduced to modulo 5, 4 is left over, then 1 is added – because the sequence of values is from 1 to 5, not from 0 to 4 – giving a final result of 5.

Listing 1 implements this formula in the for loops from line 14 and then starts outputting the combinations in the final part from line 37. The whole thing executes very quickly because the calculations are simple and the algorithm is linear, without any form of backtracking.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95

News