Skip to content

Instantly share code, notes, and snippets.

@missinglink
Last active June 25, 2023 17:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save missinglink/ee02084cfb523665e8c9d34c24f01537 to your computer and use it in GitHub Desktop.
Javascript one-liner to calculate total minesweeper neighbours
var m = [
[' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' '],
['X',' ',' ',' ',' '],
[' ','X',' ',' ',' '],
[' ',' ','X',' ',' '],
]
var m = [
[' ',' ','X'],
[' ',' ','X'],
[' ','X',' '],
['X',' ',' '],
]
// 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), []);
}
}
s = m.map(
(r,i) => r.map(
(c,j) => c=='X' ? c :
[,...m].splice(i,3).map(r=>[,...r].splice(j,3)).flat().filter(v=>v=='X').length
)
)
s.forEach(r => console.log('| ' + r.join(' | ') + ' |'))
| 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