Essays/Vier Neun

From J Wiki
Jump to navigation Jump to search

The Puzzle

From the New Scientist:

VIER and NEUN represent 4-digit squares, each letter denoting a distinct digit. You are asked to find the value of each, given the further requirement that each uniquely determines the other.

The "further requirement" means that of the numerous pairs of answers, choose the one in which each number only appears once in all of the pairs.

A Solution

The 4-digit squares are >.%:1000 squared to <.%:9999 squared, or, as a character matrix,

   s=: 4":,.*:32+i.68
   4{.s
1024
1089
1156
1225
   _4{.s
9216
9409
9604
9801

To form all pairs of such squares, catenate each row to all other rows, and make into a matrix, thus:

   p=: ,/ ,"1/ ~ s
   $p
4624 8
   4{.p
10241024
10241089
10241156
10241225
   _4{.p
98019216
98019409
98019604
98019801

The pattern of digit assignments must be the same as the pattern of letters in "vierneun", and so:

   a=: p #~ (i.~'vierneun') -:"1 i.~"1 p
   $a
9 8
   a
13694624
13695625
17645625
43561521
47615625
62419409
70561521
75691681
75694624

Finally, choose numbers that are unique in all the pairs. An item is unique if its index of first occurrence is the same as its index of last occurrence. Thus:

   a #~ (4{."1 a) *.&(i.~ = i:~) 4}."1 a
62419409

Collecting together the essential lines:

   p=: ,/ ,"1/ ~ 4 ": ,. *: 32+i.68
   a=: p #~ (i.~'vierneun')-:"1 i.~"1 p
   a #~ (4{."1 a) *.&(i.~ = i:~) 4}."1 a
62419409



See also

Vector



Contributed by Roger Hui. Substantially the same text previously appeared as a thread in the newsgroup comp.lang.apl on 2001-03-02.