private Assignment <TVar, TVal> RecursiveBacktrack(Assignment <TVar, TVal> currentAssignment, OptimizationProblem <TVar, TVal> problem, CancellationToken cancellationToken) { // This is based on an algorithm from // "Artificial Intelligence: A Modern Approach" 2nd Edition by Stuart Russel and Perter Norvig (page 142). if (currentAssignment.IsComplete(problem.Variables)) { return(currentAssignment); } cancellationToken.ThrowIfCancellationRequested(); Variable <TVar, TVal> variable = VariableSelectionStrategy.SelectUnassignedVariable(problem.Variables, currentAssignment, new Problem <TVar, TVal>(problem)); IEnumerable <TVal> domain = DomainSortStrategy.GetOrderedDomain(variable, currentAssignment, new Problem <TVar, TVal>(problem)); foreach (var value in domain) { var nextAssignment = currentAssignment.Assign(variable, value); if (this.costFunction.Cost(nextAssignment) >= this.best) { continue; } if (nextAssignment.IsConsistent(problem.Constraints)) { var result = RecursiveBacktrack(nextAssignment, problem, cancellationToken); if (result != null) { return(result); } } } return(null); }
private Var SelectUnassignedVariable(CSP <Var, Val> csp, Assignment <Var, Val> assigment) { var vars = csp.Variables.Where(v => !assigment.Contains(v)); if (VariableSelectionStrategy != null) { vars = VariableSelectionStrategy.Apply(csp, vars); } return(vars.ElementAt(0)); }
internal static SelectionStrategy ForSolver(this VariableSelectionStrategy value) => value.ForSolver(VariableSelections);
public BacktrackSolver(InferenceStrategy <Tval> infs = null, VariableSelectionStrategy <Tval> vss = null, DomainValueSelectionStragety <Tval> dvss = null) { inferenceStrategy = infs ?? new AC3 <Tval>(); variableSelectionStrategy = vss ?? new MinimumRemainingValues <Tval>(); domainValueSelectionStragety = dvss ?? new UnorderedDomainValues <Tval>(); }