Home
πŸŒ†

Skyscraper sums

Explorations on skyscraper sudokus in The J Programming language
NB. This is a comment

NB. Examples will run some code, and display their
NB. output using `NB.` as well.

3 + 4
NB. 7
NB. get the max value
>./ 1 5 3 6 7 9
NB. 9
NB. get the max value at each step
>./\ 1 5 3 6 7 9
NB. 1 5 5 6 7 9
NB. uniquify the result, only "seen" numbers
NB. count towards the total
~. >./\ 1 5 3 6 7 9
NB. 1 5 6 7 9
NB. sum the result
+/ ~. >./\ 1 5 3 6 7 9
NB. 28
NB. store as a skysum verb
skysum =: 3 : '+/ ~. >./\ y'
NB. now use it
skysum 1 5 3 6 7 9
NB. 28
NB. permutations of 0..y
perms =: i.@! A. i.
NB. permutations of 0 thru 8
perms 9
NB. 0 1 2 3 4 5 6 7 8
NB. 0 1 2 3 4 5 6 8 7
NB. 0 1 2 3 4 5 7 6 8
NB. ...
NB. add one to each
>: perms 9
NB. 1 2 3 4 5 6 7 8 9
NB. 1 2 3 4 5 6 7 9 8
NB. 1 2 3 4 5 6 8 7 9
sudo_perm =: >: perms 9
NB. filter those whose skysum is 45
(45&= @ skysum"1 # ]) sudo_perm
NB. 1 2 3 4 5 6 7 8 9
NB. abstract to a function to return rows whose
NB. skyscraper sum matches some number
skyis =: 3 : '(y&= @ skysum"1 # ]) sudo_perm'
skyis 45
NB. 1 2 3 4 5 6 7 8 9
skyis 43
NB. 1 3 2 4 5 6 7 8 9
NB. 1 3 4 2 5 6 7 8 9
NB. 1 3 4 5 2 6 7 8 9
NB. 1 3 4 5 6 2 7 8 9
NB. 1 3 4 5 6 7 2 8 9
NB. 1 3 4 5 6 7 8 2 9
NB. 1 3 4 5 6 7 8 9 2

πŸ”— Are any columns the same amongst all rows?

NB. A if A = B, else _
NB. Use "0 to only operate on integers, not rows
same =: 4 : '(x = y) { _ , x' "0

4 same 4
NB. 4
3 same 4
NB. _

1 3 2 4 5 6 7 8 9 same 1 3 4 2 5 6 7 8 9
NB. 1 3 _ _ 5 6 7 8 9
NB. map `same` over all skysums for a particular number
same/ skyis 43
NB. 1 3 _ _ _ _ _ _ _

NB. With a skyscraper sum of 43, the first cell must be
NB. a 1, and the last cell must be a 3
NB. abstract to a method

skyclues =: 3 : 'same/ skyis y'
skyclues 11
NB. 2 _ _ _ _ _ _ _ _

skyclues 43
NB. 1 3 _ _ _ _ _ _ _
Let’s put this in practice to crack the following
skyclues 34
NB. _ _ _ _ _ _ _ _ _ 

matches_219 =: 3 : '2 = _1 { y *. 1 = _2 { y *. 9 = _3 { y'"1
(matches_219 # ]) skyis 34
NB. 4 3 6 5 7 8 9 1 2
NB. 4 3 6 7 5 8 9 1 2
NB. 4 3 6 7 8 5 9 1 2

same/ (matches_219 # ]) skyis 34
NB. 4 _ _ _ _ _ 9 1 2
We now know the rightmost number is a 4.