Skip to content

Instantly share code, notes, and snippets.

@zmej-serow
Created November 5, 2021 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmej-serow/b23d4c12fb1bf1c93e177843b86c8998 to your computer and use it in GitHub Desktop.
Save zmej-serow/b23d4c12fb1bf1c93e177843b86c8998 to your computer and use it in GitHub Desktop.
Minesweeper field generator
from random import shuffle
def mine_field(size, mines_amount):
"""
в Revolut оч. любят давать эту задачу (на питоне) на собеседованиях:
Create func/class to print matrix size X/X
Fill it with Y mines (mark is as 'x') in random way (remember game minesweeper from windows?)
mark empty as 0
example result:
[ 0, 0, 'x', 'x']
['x', 0, 0, 0 ]
[ 0, 0, 0, 0 ]
[ 0, 'x', 0, 'x']
"""
def output():
return [
[
'x' if j else '0'
for j in field[i * size:(i + 1) * size]
]
for i in range(size)
]
total_fields = size * size
if mines_amount > total_fields or mines_amount < 0:
raise Exception(f'invalid mines amount, must be greater than 0 and lesser than {total_fields}')
field = [True for _ in range(mines_amount)]
field.extend([False] * (total_fields - mines_amount))
shuffle(field)
return output()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment