Exemple #1
0
        public override Assignment <VAR, VAL> solve(CSP <VAR, VAL> csp)
        {
            Assignment <VAR, VAL> assignment = new Assignment <VAR, VAL>();
            // Select a root from the List of Variables
            VAR root = _useRandom ? Util.selectRandomlyFromList(csp.getVariables()) : csp.getVariables().Get(0);
            // Sort the variables in topological order
            ICollection <VAR> orderedVars = CollectionFactory.CreateQueue <VAR>();
            IMap <VAR, IConstraint <VAR, VAL> > parentConstraints = CollectionFactory.CreateInsertionOrderedMap <VAR, IConstraint <VAR, VAL> >();

            topologicalSort(csp, root, orderedVars, parentConstraints);
            if (csp.getDomain(root).isEmpty())
            {
                return(null); // CSP has no solution! (needed if orderedVars.size() == 1)
            }
            // Establish arc consistency from top to bottom (starting at the bottom).
            csp = csp.copyDomains(); // do not change the original CSP!
            for (int i = orderedVars.Size() - 1; i > 0; i--)
            {
                VAR var = orderedVars.Get(i);
                IConstraint <VAR, VAL> constraint = parentConstraints.Get(var);
                VAR parent = csp.getNeighbor(var, constraint);
                if (makeArcConsistent(parent, var, constraint, csp))
                {
                    fireStateChanged(csp, null, parent);
                    if (csp.getDomain(parent).isEmpty())
                    {
                        return(null); // CSP has no solution!
                    }
                }
            }

            // Assign values to variables from top to bottom.
            for (int i = 0; i < orderedVars.Size(); ++i)
            {
                VAR var = orderedVars.Get(i);
                foreach (VAL value in csp.getDomain(var))
                {
                    assignment.add(var, value);
                    if (assignment.isConsistent(csp.getConstraints(var)))
                    {
                        fireStateChanged(csp, assignment, var);
                        break;
                    }
                }
            }
            return(assignment);
        }
Exemple #2
0
        /**
         * Applies an initial inference step and then calls the super class implementation.
         */

        public override Assignment <VAR, VAL> solve(CSP <VAR, VAL> csp)
        {
            if (inferenceStrategy != null)
            {
                csp = csp.copyDomains(); // do not change the original CSP!
                IInferenceLog <VAR, VAL> log = inferenceStrategy.apply(csp);
                if (!log.isEmpty())
                {
                    fireStateChanged(csp, null, null);
                    if (log.inconsistencyFound())
                    {
                        return(null);
                    }
                }
            }
            return(base.solve(csp));
        }