Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Add ability to pass custom Random to MinConflictsSolver #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 1, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions constraint/solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,24 +544,29 @@ class MinConflictsSolver(Solver):
NotImplementedError: MinConflictsSolver doesn't provide iteration
"""

def __init__(self, steps=1000):
def __init__(self, steps=1000, rand=None):
"""Initialization method.

Args:
steps (int): Maximum number of steps to perform before
giving up when looking for a solution (default is 1000)
rand (Random): Optional random.Random instance to use for
repeatability.
"""
self._steps = steps
self._rand = rand

def getSolution(self, domains: dict, constraints: list[tuple], vconstraints: dict): # noqa: D102
def getSolution(self, domains: dict, constraints: list[tuple], vconstraints: dict): # noqa: D102
choice = self._rand.choice if self._rand is not None else random.choice
shuffle = self._rand.shuffle if self._rand is not None else random.shuffle
assignments = {}
# Initial assignment
for variable in domains:
assignments[variable] = random.choice(domains[variable])
assignments[variable] = choice(domains[variable])
for _ in range(self._steps):
conflicted = False
lst = list(domains.keys())
random.shuffle(lst)
shuffle(lst)
for variable in lst:
# Check if variable is not in conflict
for constraint, variables in vconstraints[variable]:
Expand All @@ -585,7 +590,7 @@ def getSolution(self, domains: dict, constraints: list[tuple], vconstraints: dic
del minvalues[:]
minvalues.append(value)
# Pick a random one from these values.
assignments[variable] = random.choice(minvalues)
assignments[variable] = choice(minvalues)
conflicted = True
if not conflicted:
return assignments
Expand Down