I tried this script but didn't go well.
def generate_grid():
grid = np.zeros((10, 8), dtype=int)
# Fill the first row with black and the last row with white
grid[0] = 1
grid[-1] = 0
# Generate random grid until all conditions are met
while True:
grid[1:-1, :] = np.random.choice([0, 1], size=(8, 8), p=[0.5, 0.5])
if check_conditions(grid):
break
return grid
def check_conditions(grid):
# Condition 2: Check connectivity of black cells
visited_black = np.zeros(grid.shape, dtype=bool)
visited_gray = np.zeros(grid.shape, dtype=bool)
# Find black and gray cells
black_cells = np.argwhere(grid == 1)
gray_cells = np.argwhere(grid == 0)
# Check connectivity for black cells
if len(black_cells) > 0:
start_black_cell = black_cells[0]
dfs(visited_black, grid, start_black_cell)
if not np.all(visited_black[grid == 1]):
return False
# Check connectivity for gray cells
if len(gray_cells) > 0:
start_gray_cell = gray_cells[0]
dfs(visited_gray, grid, start_gray_cell)
if not np.all(visited_gray[grid == 0]):
return False
# Condition 3: Check sum of black cells
total_cells = grid.size
black_sum = np.sum(grid == 1)
if black_sum < 0.4 * total_cells or black_sum > 0.6 * total_cells:
return False
return True
def dfs(visited, grid, cell):
i, j = cell
if i < 0 or i >= grid.shape[0] or j < 0 or j >= grid.shape[1] or visited[i, j] or grid[i, j] == 0:
return
visited[i, j] = True
dfs(visited, grid, (i+1, j))
dfs(visited, grid, (i-1, j))
dfs(visited, grid, (i, j+1))
dfs(visited, grid, (i, j-1))
def plot_grid(grid):
plt.imshow(grid, cmap='binary', interpolation='nearest')
plt.xticks([])
plt.yticks([])
plt.show()
grid = generate_grid()
plot_grid(grid)
def check_conditions(grid):
# Condition 1: Check connectivity of black cells
visited = np.zeros(grid.shape, dtype=bool)
black_cells = np.argwhere(grid == 1)
if len(black_cells) == 0:
return False
start_cell = black_cells[0]
dfs(visited, grid, start_cell)
if not np.all(visited[grid == 1]):
return False
# Condition 2: Check sum of black cells
total_cells = grid.size
black_sum = np.sum(grid == 1)
if black_sum < 0.4 * total_cells or black_sum > 0.6 * total_cells:
return False
return True
when I tried this instead of the upper part, the script worked quite well as I wanted (black blocks are all connected).
However, I wanted the white part also be connected so that there is no isolated part without the connection with other clusters.
So modified the script as the top, but doesn't work. Can somebody help me?