import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
public static void showSandPile(int[][] pile){
System.out.println("Affichage du grid : ");
for(int i=0; i<pile.length; i++){
for(int j=0; j<pile[i].length; j++){
System.out.print(pile[i][j]);
}
System.out.println();
}
}
public static boolean updateSandPile(int[][] pile){
boolean startAgain = false;
for(int i=0; i<pile.length; i++){
for(int j=0; j<pile[i].length; j++){
if(pile[i][j] >= 4){
int value = 0;
value = Math.max(value, pile[i][j]-=4) ;
if(i-1 >=0)
value = Math.max(value, pile[i-1][j]+=1);
if(j-1 >=0)
value = Math.max(value, pile[i][j-1]+=1);
if(j+1 < pile[i].length)
value = Math.max(value, pile[i][j+1]+=1);
if(i+1 < pile[i].length)
value = Math.max(value, pile[i+1][j]+=1);
if(value >= 4){
startAgain = true;
}
}
}
}
return startAgain;
}
public static int [][] sandPile(int[][] pile, int n){
System.out.println("--Sand Pile--");
showSandPile(pile);
System.out.println("Ajout de " + n + " grain(s) de sable");
int middle = (pile.length/2);
//System.out.println("Ancienne valeur : " + pile[middle][middle]);
pile[middle][middle]+=n;
boolean startAgain = true;
int k=0;
while(startAgain){
k++;
//System.out.println("Tentative : " + k);
startAgain = updateSandPile(pile);
}
return pile;
}
public static void main(String[] args) {
int [][] pile;
pile = sandPile(new int[][] {
{1,1,1},
{1,3,1},
{1,1,1}
},1);
showSandPile(pile);
pile = sandPile(new int[][] {
{0,0,3,0,0},
{0,0,3,0,0},
{3,3,3,3,3},
{0,0,3,0,0},
{0,0,3,0,0},
},5);
showSandPile(pile);
pile = sandPile(new int[][] {
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,16,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
},0);
showSandPile(pile);
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: