# HG changeset patch # User Oleksandr Gavenko # Date 1411421854 -10800 # Node ID 1c3fdde0d4815041af0582b877a5bfcc05c1ca28 # Parent fc058d27e8291fef16a11521aed1ccb8c3fcdc1b Add some BoardArr function. Speedup score calculation. diff -r fc058d27e829 -r 1c3fdde0d481 board.js --- a/board.js Tue Sep 23 00:16:57 2014 +0300 +++ b/board.js Tue Sep 23 00:37:34 2014 +0300 @@ -24,6 +24,16 @@ BoardArr.prototype.set = function(i, j, val) { this.brd[4*i + j] = val; } +/** Compare boards. */ +BoardArr.prototype.equals = function(brd) { + var from = this.brd, to = brd.brd; + // More often corners differ, check it first. + return from[0] === to[0] && from[3] === to[3] && from[12] === to[12] && from[15] === to[15] + && from[1] === to[1] && from[2] === to[2] + && from[4] === to[4] && from[5] === to[5] && from[6] === to[6] && from[7] === to[7] + && from[8] === to[8] && from[9] === to[9] && from[10] === to[10] && from[11] === to[11] + && from[13] === to[13] && from[14] === to[14]; +} /* Return and optionally fill 2d board. * Doesn't designed to be efficient. */ BoardArr.prototype.exportTo = function(brd) { @@ -39,6 +49,32 @@ brd.brd[i] = this.brd[i]; return brd; } +/** Number of free cell. */ +BoardArr.prototype.free = function() { + var cnt = 0; + for (var i = 0; i < 16; i++) + if (this.brd[i] === 0) + cnt++; + return cnt; +} +BoardArr.prototype.score = function() { + var score = 0; + for (var i = 0; i < 16; i++) { + var v = this.brd[i][j]; + if (v > 1) + score += (v-1)*(1 << v); + } + return score; +} +BoardArr.prototype.max = function() { + var max = 0; + for (var i = 0; i < 4; i++) { + for (var j = 0; j < 4; j++) { + max = Math.max(max, this.brd[i][j]); + } + } + return max; +} @@ -81,6 +117,7 @@ && x1[0] === y1[0] && x1[1] === y1[1] && x1[2] === y1[2] && x1[3] === y1[3] && x2[0] === y2[0] && x2[1] === y2[1] && x2[2] === y2[2] && x2[3] === y2[3]; } +/** Compare boards. */ BoardArr2d.prototype.equals = BoardArr2d.prototype.equals_unrolled; /* Return and optionally fill 2d board. */ @@ -98,6 +135,7 @@ brd.brd[i][j] = this.brd[i][j]; return brd; } +/** Number of free cell. */ BoardArr2d.prototype.free = function() { var cnt = 0; for (var i = 0; i < 4; i++) @@ -111,8 +149,8 @@ for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { var v = this.brd[i][j]; - if (v > 0) - score += (v-1)*Math.pow(2, v); + if (v > 1) + score += (v-1)*(1 << v); } } return score; @@ -764,6 +802,7 @@ brd[i][j] = this.brd[4*i + j]; return brd; } +/** Compare boards. */ BoardObj.prototype.equals = function(brd) { var self = this.brd; return self.aa == brd.aa && self.ad == brd.ad && self.da == brd.da && self.dd == brd.dd @@ -789,6 +828,7 @@ brd.da = self.da; brd.db = self.db; brd.dc = self.dc; brd.dd = self.dd; return brd; } +/** Number of free cell. */ BoardObj.prototype.free = function() { var cnt = 0; var brd = this.brd;