1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
var W=7,H=8;
function emptyboard(){
return new Array(H).fill(0).map(function(){
return new Array(W).fill(0).map(function(){
return {n:0,c:0};
});
});
}
function bdcopy(bd){
return bd.map(function(r){
return r.map(function(c){
return {n:c.n,c:c.c};
});
});
}
function checkwin(bd){
var wincolour=-1,i;
for(i=0;i<W*H;i++){
if(bd[~~(i/W)][i%W].n){
if(wincolour==-1)wincolour=bd[~~(i/W)][i%W].c
else if(bd[~~(i/W)][i%W].c!=wincolour)return -1;
}
}
return wincolour;
}
function countballs(bd){
var count=0;
var x,y;
for(y=0;y<H;y++)for(x=0;x<W;x++)count+=bd[y][x].n;
return count;
}
function stabilise(bd){
var newbd;
var changes;
var x,y,nnei,quo;
do {
changes=false;
newbd=bdcopy(bd);
for(y=0;y<H;y++){
for(x=0;x<W;x++){
nnei=(y>0)+(x>0)+(y<H-1)+(x<W-1);
if(bd[y][x].n>=nnei){
quo=~~(bd[y][x].n/nnei);
newbd[y][x].n-=quo*nnei;
if(y>0) {newbd[y-1][x].n+=quo;newbd[y-1][x].c=bd[y][x].c;}
if(x>0) {newbd[y][x-1].n+=quo;newbd[y][x-1].c=bd[y][x].c;}
if(y<H-1){newbd[y+1][x].n+=quo;newbd[y+1][x].c=bd[y][x].c;}
if(x<W-1){newbd[y][x+1].n+=quo;newbd[y][x+1].c=bd[y][x].c;}
changes=true;
}
}
}
bd=newbd;
if(checkwin(bd)!=-1)break;
} while(changes);
return bd;
}
Array.prototype.fill=Array.prototype.fill||function(t){if(null==this)throw new TypeError("this is null or not defined");for(var r=Object(this),n=r.length>>>0,i=arguments[1],a=i>>0,e=0>a?Math.max(n+a,0):Math.min(a,n),o=arguments[2],h=void 0===o?n:o>>0,l=0>h?Math.max(n+h,0):Math.min(h,n);l>e;)r[e]=t,e++;return r};
|