# HG changeset patch # User Oleksandr Gavenko # Date 1470600851 -10800 # Node ID dbf2da029e02d748d38fd134cb727b1d6a555d95 # Parent 59df68b203ca762783d74bcfbd28f27b61b28c0c Add missing implementation: Monte-Carlo AI require 'rnd' method in board object. diff -r 59df68b203ca -r dbf2da029e02 board.js --- a/board.js Sat Feb 06 14:34:51 2016 +0200 +++ b/board.js Sun Aug 07 23:14:11 2016 +0300 @@ -71,6 +71,22 @@ cnt++; return cnt; } +/** Put random value to free cell uniformly. */ +BoardArr.prototype.rnd = function(val) { + var brd = this.brd; + var idx; + var free = 0; + for (var i = 0; i < 16; i++) { + if (brd[idx] === 0) { + free++; + if (Math.random()*free < 1) + idx = i; + } + } + if (free === 0) + throw new Error('There are no free space...'); + brd[idx] = val; +} BoardArr.prototype.score = function() { var score = 0; for (var i = 0; i < 16; i++) { @@ -178,6 +194,24 @@ cnt++; return cnt; } +/** Put random value to free cell uniformly. */ +BoardArr2d.prototype.rnd = function(val) { + var brd = this.brd; + var xi, xj; + var free = 0; + for (var i = 0; i < 4; i++) + for (var j = 0; j < 4; j++) + if (this.brd[i][j] === 0) { + free++; + if (Math.random()*free < 1) { + xi = i; + xj = j; + } + } + if (free === 0) + throw new Error('There are no free space...'); + brd[xi][xj] = val; +} BoardArr2d.prototype.score = function() { var score = 0; for (var i = 0; i < 4; i++) {