DEV Community

loading...

Discussion on: Daily Challenge #279 - Playing with Sandpiles

Collapse
bubbler4 profile image
Bubbler • Edited

APL (using Dyalog APL):

add←{{(+/4≤⊢/4 2⍴⍵)+4|⍵[2;2]}⌺3 3⍣≡⍺+⍵}

(Use the bookmarklet on this post to see the code with APL font and syntax highlighting.)

Takes two 3-by-3 matrices as the left and right arguments. Full demo can be found here. The task is a great showcase for APL's array manipulation abilities.

Explanation:

add←{{(+/4≤⊢/4 2⍴⍵)+4|⍵[2;2]}⌺3 3⍣≡⍺+⍵}
{...}      ⍝ Function definition
⍺+⍵        ⍝ Add two arguments, element-wise
...⍣≡      ⍝ Repeat until converges...
{...}⌺3 3  ⍝  Apply the subfunction to 3×3 submatrices...
4|⍵[2;2]   ⍝   The center value, minus 4 if too high
(...)+     ⍝   Add topples from its neighbors...
4 2⍴⍵      ⍝    Reshape to 4×2 matrix,
           ⍝    putting all 4-neighbors on the right column
4≤⊢/       ⍝    Extract right column, test each number for 4≤
+/         ⍝    Sum the ones (count the topples)