APL, 53 49 43 42 40 39 36
I managed to replicate J's ;.
in APL, and used Gareth's approachGareth's approach, saving 13 chars.
{×5⌷⍵:5⌷⍵⋄+/⍵}¨3,⌿3,/×∘?∘9¨∘.∨⍨9⍴0 1
Sample run:
{×5⌷⍵:5⌷⍵⋄+/⍵}¨3,⌿3,/×∘?∘9¨∘.∨⍨9⍴0 1
9 9 6 1 7 5 6
7 55 5 39 9 54 9
9 8 2 1 8 1 9
2 43 8 41 6 42 5
7 3 4 4 8 3 2
2 29 1 26 2 35 8
6 4 2 3 2 3 7
Explanation:
∘.∨⍨9⍴0 1
generates a bit mask.×∘?∘9¨
multiplies each bit by a random value from 1 to 9 inclusive, generating a masked grid of random numbers.3,⌿3,/
uses what can only be described as hackery to return all 3 by 3 overlapping boxes in the masked array. These are also flattened in the process.{×5⌷⍵:5⌷⍵⋄+/⍵}¨
iterates over the array, assigning each element to⍵
. For each iteration, it takes the fifth (middle, remembering that APL indexing is 1-based), and returns its sign. In this case this is equivalent to testing if the number is greater than 0. If this returns 1 (for true), then return that element. Otherwise, return the sum of the elements in the flattened 3 by 3 box. It uses the:⋄
ternary operator, which is the equivalent of?:
in many languages.