Created
November 5, 2021 18:28
-
-
Save zmej-serow/b23d4c12fb1bf1c93e177843b86c8998 to your computer and use it in GitHub Desktop.
Minesweeper field generator
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
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