Last active
March 10, 2022 18:53
-
-
Save edrdesigner/5014f57e55c7f4189daeed48d19c3d5b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Javascript one-liner to calculate total minesweeper neighbours | |
// Polyfill for ECMA 2019 | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat | |
if (!Array.prototype.flat) { | |
Array.prototype.flat = function () { | |
return this.reduce((acc, val) => acc.concat(val), []); | |
} | |
} | |
var input1 = [ | |
[' ',' ',' ',' ',' '], | |
[' ',' ',' ',' ',' '], | |
['X',' ',' ',' ',' '], | |
[' ','X',' ',' ',' '], | |
[' ',' ','X',' ',' '], | |
] | |
var input2 = [ | |
[' ',' ','X'], | |
[' ',' ','X'], | |
[' ','X',' '], | |
['X',' ',' '], | |
]; | |
function findNeighbors(input) { | |
return input.map( | |
(r,i) => r.map( | |
(c, j) => { | |
if (c == 'X') return c; | |
return [, ...input] | |
.splice(i, 3) | |
.map(r => [,...r] | |
.splice(j, 3)) | |
.flat() | |
.filter(cell => cell == 'X').length | |
} | |
) | |
); | |
} | |
function mountConsoleBoard(output) { | |
output.forEach(r => console.log('| ' + r.join(' | ') + ' |')) | |
} | |
mountConsoleBoard(findNeighbors(input2)); | |
// Output | |
/** | |
| 0 | 2 | X | | |
| 1 | 3 | X | | |
| 2 | X | 2 | | |
| X | 2 | 1 | | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment