What surrounds my Minesweeper tile?
APL (Dyalog Unicode), 28 15 bytes
-13 bytes thanks to ngn!
{3 3⍴5⌽⍵,⍵≥8?8}
Explanation:
{...}
A direct function (D-Fn), ⍵
is its right argument.
8?8
deal 8 random numbers from the list 1..8:
8?8
7 2 1 8 4 6 5 3
⍵≥
is the argument greater or equal to each of them?:
5 ≥ 7 2 1 8 4 6 5 3
0 1 1 0 1 0 1 1
⍵,
prepend the argument to the boolean list:
5 , 0 1 1 0 1 0 1 1
5 0 1 1 0 1 0 1 1
5⌽
rotate the list 5 positions to the left, so that the argument is in the center:
5 ⌽ 5 0 1 1 0 1 0 1 1
1 0 1 1 5 0 1 1 0
3 3⍴
reshape the list to a 3x3 matrix:
3 3 ⍴ 1 0 1 1 5 0 1 1 0
1 0 1
1 5 0
1 1 0
Try it online!
J, 15 bytes
Also many bytes thanks to ngn!
3 3$5|.],]>8?8:
Try it online!
JavaScript (ES6), 67 bytes
Shorter version suggested by @tsh
Empty slots are 0
, mines are 1
.
n=>`___
_${t=9,n}_
___`.replace(/_/g,_=>n-(n-=Math.random()<n/--t))
Try it online!
Original trial-and-error version, 78 bytes
Empty slots are _
, mines are 7
.
f=(n,o=`___
_${k=n}_
___`.replace(/_/g,c=>Math.random()<.5?--k|7:c))=>k?f(n):o
Try it online!
Commented
f = ( // f = recursive function
n, // n = input
o = `___\n_${k = n}_\n___` // o = minesweeper field / k = backup of n
.replace(/_/g, c => // for each underscore character c in o:
Math.random() < .5 ? // random action:
--k | 7 // either decrement k and yield 7
: // or:
c // let the underscore unchanged
) // end of replace()
) => //
k ? // if k is not equal to 0:
f(n) // try again
: // else:
o // stop recursion and return o
Jelly, 13 10 bytes
8Ẉ>RẊs4js3
The returned list of lists has the displayed integer in the centre surrounded by 0s and 1s representing mines and blanks respectively.
Try it online! (footer pretty prints the array)
How?
8Ẉ>RẊs4js3 - Link: integer, n e.g. 3
8 - eight 8
Ẉ - length of each (implicit range of eight) [1,1,1,1,1,1,1,1]
R - range of n [1,2,3]
> - greater than? (vectorises) [0,0,0,1,1,1,1,1]
Ẋ - shuffle [1,1,1,0,0,1,1,0]
s4 - split into chunks of 4 [[1,1,1,0],[0,1,1,0]]
j - join (with n) [1,1,1,0,3,0,1,1,0]
s3 - split into chunks of 3 [[1,1,1],[0,3,0],[1,1,0]]