Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

6 of 6
edited body
Galen Ivanov
  • 21.5k
  • 3
  • 26
  • 62

J, (削除) 67 (削除ここまで) 65 bytes

A naïve and verbose solution in J. It is a straightforward implementation of the task.

(+/^:_"2((,&.>/@(<:,],>:)"0)&.>m){0 m}a)(m=.{;~1 3 5)}a=.>:?7 79ドル

First I create a 7 x 7 array of integers between 1 and 9. In fact J's ? verb generates numbers up to its argument, that's why we need to increment each element, >: in J

a=.>:?7 79ドル 
2 8 7 4 4 5 1
4 5 4 1 6 7 9
3 8 3 6 5 3 3
6 8 6 3 7 7 1
7 7 4 4 5 9 9
2 3 6 5 2 2 9
2 2 6 8 8 1 3

I prepare a mask to be used for zeroing of the odd row/col cells, a pairs of odd row/column indices:

m=.{;~1 3 5
┌───┬───┬───┐
│1 1│1 3│1 5│
├───┼───┼───┤
│3 1│3 3│3 5│
├───┼───┼───┤
│5 1│5 3│5 5│
└───┴───┴───┘

The Catalogue verb { combines items from the atoms inside the boxed list

┌─────┬─────┐
│1 3 5│1 3 5│
└─────┴─────┘

to form a catalogue, the 3x3 table of the pairs above

Then I prepare a table of row/col indices to be used for selection of each of the 3x3 subarrays.

s=.(,&.>/@(<:,],>:)"0)&.>m
┌─────────────┬─────────────┬─────────────┐
│┌─────┬─────┐│┌─────┬─────┐│┌─────┬─────┐│
││0 1 2│0 1 2│││0 1 2│2 3 4│││0 1 2│4 5 6││
│└─────┴─────┘│└─────┴─────┘│└─────┴─────┘│
├─────────────┼─────────────┼─────────────┤
│┌─────┬─────┐│┌─────┬─────┐│┌─────┬─────┐│
││2 3 4│0 1 2│││2 3 4│2 3 4│││2 3 4│4 5 6││
│└─────┴─────┘│└─────┴─────┘│└─────┴─────┘│
├─────────────┼─────────────┼─────────────┤
│┌─────┬─────┐│┌─────┬─────┐│┌─────┬─────┐│
││4 5 6│0 1 2│││4 5 6│2 3 4│││4 5 6│4 5 6││
│└─────┴─────┘│└─────┴─────┘│└─────┴─────┘│
└─────────────┴─────────────┴─────────────┘

For each pair in the m array I make a pair of triplets, centered around each number of the m pair:

 ┌─────┬─────┐
 1 3 -> │0 1 2│2 3 4│
 └─────┴─────┘

These pairs of triplets are used by the J From verb {, which can select multiple rows and columns simultaneously. 0 1 2 / 2 3 4 means that I select rows 0, 1 and 2 together with columns 2, 3 and 4, thus selecting the second 3x3 subarray on the top.

Finally, I can use the 7x7 array and the masks to achieve the task: First I use m as a mask to set the corresponding elements to 0:

0 m}a

Then I take all the 3x3 subarrays using s as a selector and find their sums:

+/^:_"2 s{0 m}a

Then I put these numbers back into the starting array.

 (+/^:_"2 s{0 m}a)m}a 
2 8 7 4 4 5 1
4 39 4 39 6 36 9
3 8 3 6 5 3 3
6 44 6 40 7 42 1
7 7 4 4 5 9 9
2 36 6 43 2 46 9
2 2 6 8 8 1 3

Try it online!

Galen Ivanov
  • 21.5k
  • 3
  • 26
  • 62

AltStyle によって変換されたページ (->オリジナル) /