Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function c(m, n) {
- var val = 1
- for (let temp = m; temp > m - n; temp--) {
- val = val * temp / (temp - m + n)
- }
- return val;
- }
- function p(w, h) {
- return function ptr(x, y) {
- var pos = {x, y}
- pos.next = function () {
- if (x < 0 || x >= w || y < 0 && y >= h) {
- return null;
- }
- // highest valid pointer
- if (x >= w - 1 && y >= h - 1) {
- return null;
- }
- if (x < w - 1) {
- return ptr(x + 1, y);
- } else {
- return ptr(0, y + 1);
- }
- }
- if (x >= 0 && x < w && y >= 0 && y < h) {
- pos.offset = x + y * w;
- } else {
- pos.offset = null;
- }
- pos.neighbors = function() {
- return [
- ptr(x - 1, y - 1),
- ptr(x, y - 1),
- ptr(x + 1, y - 1),
- ptr(x - 1, y),
- ptr(x + 1, y),
- ptr(x - 1, y + 1),
- ptr(x, y + 1),
- ptr(x + 1, y + 1)
- ]
- }
- return pos
- }
- }
- function t(w, h, init, outBoundVal) {
- var data = [];
- var Ptr = p(w, h);
- function table(ptr, val) {
- if (val != null) {
- if (ptr.offset != null) {
- data[ptr.offset] = val
- }
- } else {
- if (ptr.offset != null) {
- return data[ptr.offset]
- } else {
- return outBoundVal
- }
- }
- }
- table.w = w
- table.h = h
- table.data = data
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- data[ptr.offset] = init;
- }
- table.clone = function () {
- var newTable = t(w, h, init, outBoundVal);
- var ptr = p(w, h)(0, 0);
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- newTable(ptr, table(ptr));
- }
- return newTable
- }
- //regex must has global flag
- table.countRegex = function(regex) {
- var counter = 0
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- if (regex.test(table(ptr))) {
- counter += 1;
- }
- }
- return counter;
- }
- table.count = function (val) {
- var counter = 0
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- if (table(ptr) === val) {
- counter += 1;
- }
- }
- return counter;
- }
- table.toString = function () {
- var res = []
- for (var i = 0; i < data.length; i += w) {
- res.push(data.slice(i, i + w).join(', '));
- }
- return res.join('\r\n');
- }
- return table;
- }
- function resolve(w, h, totalMines, str) {
- /*
- '-': unknown
- 'x': empty
- 'o': bomb
- '0' - '9': count near by
- */
- var table = t(w, h, '-', 'x')
- // init
- var Ptr = p(w, h);
- var ptr = Ptr(0, 0);
- var temp = str.replace(/[\r\n]/g, '');
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- table(ptr, temp.slice(ptr.offset, ptr.offset + 1));
- }
- // found slot with no no number neighbors
- // true: has neighbor
- // false: no neighbor
- var mask = t(w, h, false, false)
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- let neightborPtrs = ptr.neighbors();
- mask(ptr, neightborPtrs.reduce(function (prev, ptr) {
- var val = table(ptr)
- return prev || !!val.match(/[0-9]/);
- }, false))
- }
- var unPredicableSlots = mask.count(false);
- var totalFoundMines = table.count('o')
- var minesLeft = totalMines - totalFoundMines;
- // situation when there are n mines drops in unprediactable area;
- var unPredicableMultiplier = {}
- var combinationCounts = {}
- var guessTables = [];
- for (let unPredicableCount = minesLeft - 1; unPredicableCount >= 0; unPredicableCount--) {
- unPredicableMultiplier[unPredicableCount] = c(unPredicableSlots, unPredicableCount);
- combinationCounts[unPredicableCount] = 0;
- guessTables[unPredicableCount] = t(w, h, 0, 0);
- }
- // solve until there is no other possible combination
- function solve(ptr, currentTable, minesLeft) {
- // move until guessable Slot
- while (ptr && (!mask(ptr) || currentTable(ptr) !== '-')) {
- ptr = ptr.next();
- }
- if (!ptr && minesLeft >= 0) {
- // found a possible solution;
- // console.log('hit #' + combinationCounts[minesLeft] + '\r\n' + currentTable.toString());
- combinationCounts[minesLeft] += 1;
- for (var ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- if (mask(ptr)) {
- var guessTable = guessTables[minesLeft]
- if (currentTable(ptr) === 'o') {
- guessTable(ptr, guessTable(ptr) + 1)
- }
- }
- }
- return;
- }
- // check if this slot can be mine or not be mine
- // and abort the branch if that branch failed;
- var neightbors = ptr.neighbors();
- var canBeMine = true;
- var canBeEmpty = true;
- neightbors.forEach(function (neightbor) {
- if (currentTable(neightbor).match(/[0-9\s]/)) {
- var neightborsOfNeighbor = neightbor.neighbors();
- var number = currentTable(neightbor);
- number = number === ' ' ? 0 : parseInt(number, 10)
- var minesNearBy = neightborsOfNeighbor.reduce(function (prev, curr) {
- if (currentTable(curr) === 'o') {
- return prev + 1;
- } else {
- return prev;
- }
- }, 0);
- var emptyNearBy = neightborsOfNeighbor.reduce(function (prev, curr) {
- if (currentTable(curr).match(/[0-9x\s]/)) {
- return prev + 1;
- } else {
- return prev;
- }
- }, 0);
- var unknownNearBy = 8 - minesNearBy - emptyNearBy;
- var minesToPlace = number - minesNearBy;
- if (minesToPlace === unknownNearBy) canBeEmpty = false;
- if (minesToPlace === 0) canBeMine = false;
- }
- })
- if (canBeMine && minesLeft !== 0) {
- var newTable = currentTable.clone();
- newTable(ptr, 'o')
- solve(ptr.next(), newTable, minesLeft - 1)
- // we still has mine, and we can put mine here
- }
- if (canBeEmpty) {
- var newTable = currentTable.clone();
- newTable(ptr, 'x')
- solve(ptr.next(), newTable, minesLeft)
- }
- // if (!canBeMine && !canBeEmpty) {
- // console.log('badGuess\r\n' + currentTable)
- // }
- }
- solve(Ptr(0, 0), table.clone(), minesLeft);
- // console.log(unPredicableMultiplier)
- // console.log(combinationCounts)
- // console.log(guessTables.map(function (table, i) {
- // return '# guessTable ' + i + '\r\n' + table.toString();
- // }).join('\r\n'))
- // sum up the possibility
- var finalBoardCount = 0;
- var finalBoard = t(w, h, 0, 0);
- for (let unPredicableCount = minesLeft - 1; unPredicableCount >= 0; unPredicableCount--) {
- finalBoardCount += (unPredicableMultiplier[unPredicableCount] * combinationCounts[unPredicableCount]);
- // init possibility for unPredicable slot;
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- if (!mask(ptr)) {
- guessTables[unPredicableCount](ptr, combinationCounts[unPredicableCount] * (unPredicableCount / unPredicableSlots))
- }
- }
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- finalBoard(ptr, finalBoard(ptr) + guessTables[unPredicableCount](ptr) * unPredicableMultiplier[unPredicableCount])
- }
- }
- if (finalBoardCount === 0) {
- throw new Error('invalid board')
- }
- function formatToPercent(num, small) {
- small = small || 2;
- var val = parseFloat(num * 100).toFixed(small) + "%";
- // xxx.<small>
- var totalLength = small + 5;
- while (val.length < totalLength) {
- val = ' ' + val
- }
- return val;
- }
- var finalBoardPercent = t(w, h, "", "");
- for (let ptr = Ptr(0, 0); ptr; ptr = ptr.next()) {
- finalBoard(ptr, finalBoard(ptr) / finalBoardCount);
- finalBoardPercent(ptr, formatToPercent(finalBoard(ptr)));
- if (table(ptr) !== '-') {
- finalBoard(ptr, -1);
- finalBoardPercent(ptr, ' <N/A>')
- }
- }
- console.log('board with ' + totalMines + ' mines')
- console.log(table.toString())
- console.log('result is')
- console.log(finalBoardPercent.toString());
- }
- /*
- resolve(7, 8, 15, `
- -------
- -----2-
- o312o--
- o--o4o-
- ---o42-
- ---o---
- -----o-
- -------
- `)
- */
- var readline = require('readline')
- const rl = readline.createInterface({
- input: process.stdin,
- output: process.stdout
- });
- console.log(`The board are in this format
- '-': unknown
- 'x': empty
- 'o': bomb
- '0' - '9': mine count near by
- And should format in
- ---x
- -13o
- ----
- this way
- `)
- rl.question('What is the width?\r\n', (w) => {
- w = parseInt(w, 10)
- rl.question('What is the height?\r\n', (h) => {
- h = parseInt(h, 10)
- rl.question('How many mines are on the board?\r\n', (totalMine) => {
- totalMine = parseInt(totalMine, 10)
- var board = '';
- var n = 0;
- function nextLine(){
- rl.once('line', (line)=>{
- n += 1;
- board += (line + '\r\n');
- if (n < h) {
- nextLine()
- } else {
- console.log(w, h, totalMine, board)
- resolve(w, h, totalMine, board)
- rl.close();
- process.stdin.end()
- }
- })
- }
- console.log('please send me the board')
- nextLine()
- })
- })
- });
Advertisement
Add Comment
Please, Sign In to add comment