Skip to content

Instantly share code, notes, and snippets.

@leynier
Last active October 26, 2020 00:17
Show Gist options
  • Save leynier/673309c6c921161beda18b26f7016888 to your computer and use it in GitHub Desktop.
Save leynier/673309c6c921161beda18b26f7016888 to your computer and use it in GitHub Desktop.
def generate(n_rows, n_cols, ratio, diff):
hidato_solved = generate_hidato_solved(n_rows, n_cols, ratio)
max_elem = n_rows * n_cols - count_obstacles(hidato_solved)
cells_for_remove = random_shuffle(filter(lambda cell: get_cell_value(cell) > 1 and get_cell_value(cell) < max_elem, get_cells(hidato_solved)))
cant_empty = floor(len(cells_for_remove) * diff)
template = remove_cells(hidato_solved, n_rows, n_cols, cells_for_remove, cant_empty)
return template
def generate_hidato_solved(n_rows, n_cols, ratio):
pseudo_template = generate_random_pseudo_template(n_rows, n_cols, ratio)
limit = n_rows * n_cols - count_obstacles(pseudo_template)
solves = solve(pseudo_template, 0, limit)
if solves:
return solves[0]
else:
return generate_hidato_solved(n_rows, n_cols, ratio)
def generate_random_pseudo_template(n_rows, n_cols, ratio):
cant_obs = floor(n_rows * n_cols * ratio)
blank_template = create_black_template(n_rows, n_cols)
cells_for_remove = take(cant_obs, random_shuffle(get_cells(blank_template)))
dark_template = reduce(lambda acc, cell: update_cell_in_table(acc, update_value_in_cell(-1, cell)), cells_for_remove, blank_template)
pseudo_template = update_cell_in_table(dark_template, update_value_in_cell(1, select_random_cell(dark_template)))
return pseudo_template
def remove_cells(template, n_rows, n_cols, cells_for_remove, cant_empty):
if not cells_for_remove or cant_empty < 0:
return template
else:
head_cell = cells_for_remove[0]
tail_cells = cells_for_remove[1:]
empty = update_value_in_cell(0, head_cell)
new_template = update_cell_in_table(template, empty)
limit = n_rows * n_cols - count_obstacles(new_template)
solves = solve(new_template, 0, limit)
if len(take(2, solves)) < 2:
return remove_cells(new_template, n_rows, n_cols, tail_cells, cant_empty - 1)
else:
return remove_cells(template, n_rows, n_cols, tail_cells, cant_empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment