## DEV Community is a community of 890,377 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Daily Challenge #279 - Playing with Sandpiles

Bubbler • Edited on

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)
``````