12
(There are related questions about infinite sandpiles, and finding identity elements of sandpiles.)
Given a matrix of non-negative integers, return a matrix of the same dimensions, but toppled:
- If the matrix doesn't contain any values larger than 4, return it.
- Every "cell" that is larger than 3 gets reduced by 4, and all directly neighboring cells (above, below, left, and right) are incremented, if they exist.
- GOTO 1.
Examples:
0 1 0 0 2 0
2 4 0 -> 3 0 1
0 0 3 0 1 3
1 2 3 2 3 4 2 5 1 4 1 2 0 3 3 0 3 3 0 3 3
4 5 6 -> 2 4 4 -> 4 2 3 -> 0 5 4 -> 3 2 1 -> 3 3 1 -> 3 3 2
7 8 9 5 7 7 2 6 5 4 3 2 0 5 3 1 1 4 1 2 0
(You only need to return the final result. The path on which you reach it may differ from the one shown here: it doesn't matter in which order you perform the toppling operations, they all lead to the same result.)
For a deeper explanation and some motivation see this Numberphile video or the Wikipedia article on the Abelian sandpile model.
Rules:
- You may take input and output in any of the standard ways
- Loopholes are forbidden
- Input and output may be:
- a nested list:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- a simple list:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
and the shape - some kind of native matrix type
- a string, e.g.
1 2 3\n4 5 6\n7 8 9
- or whatever else works in your language.
- a nested list:
- Input and output must be in the same form
- The input may contain larger numbers than the ones shown here, but the size may be bound by the limits of your language (MAXINT equivalents, if applicable)
- The matrix may have any shape (e.g. 1x1, 2x2, 3x3, 4x4, 2x7, 11x3, ...)
- You don't need to handle the case where the shape is 0xN or Nx0.
Testcases
[[2, 5, 4], [8, 6, 4], [1, 2, 3]] -> [[3, 3, 0], [1, 2, 2], [1, 3, 2]]
[[0, 0, 2], [1, 3, 3], [0, 0, 0]] -> [[0, 0, 2], [1, 3, 3], [0, 0, 0]]
[[9, 9, 9], [9, 9, 9], [9, 9, 9]] -> [[1, 3, 1], [3, 1, 3], [1, 3, 1]]
[[4, 5], [2, 3]] -> [[2, 3], [0, 1]]
[[2, 3, 5], [2, 2, 0]] -> [[3, 0, 2], [2, 3, 1]]
[[7]] -> [[3]]
This is codegolf, the shortest code (per language) wins.
Is it OK to display all the intermediate results? – feersum – 2017-03-30T13:29:04.150
@feersum I guess so, as long as it's clear what the final result is. – L3viathan – 2017-03-30T13:38:07.587