package jrummikub.ai.fdsolver.constraint; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import jrummikub.ai.fdsolver.Constraint; import jrummikub.ai.fdsolver.Propagator; import jrummikub.ai.fdsolver.Satisfiability; import jrummikub.ai.fdsolver.Var; public class IndexConstraint implements Constraint { Var target; Var index; List> list; Collection> vars = new ArrayList>(); Collection> varsNoTarget = new ArrayList>(); Collection> varsNoIndex = new ArrayList>(); public IndexConstraint(Var target, Var index, List> list) { this.target = target; this.index = index; this.list = list; vars.addAll(list); vars.add(index); vars.add(target); varsNoTarget.addAll(list); varsNoTarget.add(index); varsNoIndex.addAll(list); varsNoIndex.add(target); } @Override public Collection> getWatchedVars() { return vars; } private class UnionProp implements Propagator { @Override public Collection> getWatchedVars() { return varsNoTarget; } @Override public void propagate() { HashSet union = new HashSet(); for (int i : index.getRange()) { union.addAll(list.get(i).getRange()); } for (Iterator i = target.iterator(); i.hasNext();) { T val = i.next(); if (!union.contains(val)) { i.remove(); } } }; } private class IndexProp implements Propagator { @Override public Collection> getWatchedVars() { return varsNoIndex; } @Override public void propagate() { for (Iterator i = index.iterator(); i.hasNext();) { int id = i.next(); HashSet range = new HashSet(target.getRange()); range.retainAll(list.get(id).getRange()); if (range.isEmpty()) { i.remove(); } } } } private class VarProp implements Propagator { @Override public Collection> getWatchedVars() { return Arrays.asList(target, index); } @Override public void propagate() { if (index.getRange().size() != 1) return; int id = index.getValue(); Var var = list.get(id); for(Iterator i = var.iterator(); i.hasNext();) { if (!target.getRange().contains(i.next())) { i.remove(); } } } } @Override public Collection getPropagators(boolean negate) { if (negate) { return Collections.emptyList(); } return Arrays. asList(new UnionProp(), new IndexProp(), new VarProp()); } @Override public Satisfiability getSatisfiability() { HashSet union = new HashSet(); for (int i : index.getRange()) { union.addAll(list.get(i).getRange()); } boolean isSat = false; for (T val : target.getRange()) { if (union.contains(val)) { isSat = true; break; } } if (!isSat) { return Satisfiability.UNSAT; } else { if (union.size() == 1 && target.getRange().size() == 1) { return Satisfiability.TAUT; } else { return Satisfiability.SAT; } } } }