public Assignment <TVar, TVal> Optimize(OptimizationProblem <TVar, TVal> problem) { var currentAssignment = Solve(problem); var nextAssignment = currentAssignment; while (nextAssignment != null) { this.best = this.costFunction.Cost(currentAssignment); nextAssignment = Solve(problem); if (nextAssignment != null) { currentAssignment = nextAssignment; } } return(currentAssignment); }
public Problem(OptimizationProblem <TVar, TVal> oProblem) : this(oProblem.Variables, oProblem.Constraints, oProblem.InitialAssignment) { }
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); }
/// <summary> /// Attempts to solve the specified constraint satisfaction problem. /// If the problem could not be solved then this will return null. /// </summary> /// <param name="problem">the problem to solve</param> /// <returns>a complete assignment or null</returns> /// <exception cref="ArgumentNullException">if the problem is null</exception> public Assignment <TVar, TVal> Solve(OptimizationProblem <TVar, TVal> problem) { return(Solve(problem, CancellationToken.None)); }