NotEqual.java

  1. /* Copyright 2015 Laurent COCAULT
  2.  * Licensed to Laurent COCAULT under one or more contributor license agreements.
  3.  * See the NOTICE file distributed with this work for additional information
  4.  * regarding copyright ownership. Laurent COCAULT licenses this file to You
  5.  * under the Apache License, Version 2.0 (the "License"); you may not use this
  6.  * file except in compliance with the License.  You may obtain a copy of the
  7.  * License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.csp.constraint.model.general;

  18. import org.csp.constraint.model.BinaryConstraint;
  19. import org.csp.constraint.model.Variable;

  20. /**
  21.  * Binary constraint specifying that two variables are different.
  22.  */
  23. public class NotEqual<T> extends BinaryConstraint<T> {

  24.     /**
  25.      * Constructor for constraint "left != right".
  26.      * @param left
  27.      *            Left variable
  28.      * @param right
  29.      *            Right variable
  30.      */
  31.     public NotEqual(final Variable<T> left, final Variable<T> right) {
  32.         super(left.getName() + " != " + right.getName(), left, right);
  33.     }

  34.     /**
  35.      * {@inheritDoc}
  36.      */
  37.     @Override
  38.     public void propagate() {

  39.         // The current implementation of the propagation is not as efficient as
  40.         // it could be.
  41.         // TODO Enhancement

  42.         // Get the two variables concerned
  43.         final Variable<T> first = getFirstVariable();
  44.         final Variable<T> second = getSecondVariable();

  45.         // Propagate on the first variable
  46.         if (second.isBound()) {
  47.             if (first.removeValue(second.getValue())) {
  48.                 addRecentChangedVariable(first);
  49.             }
  50.         }

  51.         // Propagate on the second variable.
  52.         if (first.isBound()) {
  53.             if (second.removeValue(first.getValue())) {
  54.                 addRecentChangedVariable(second);
  55.             }
  56.         }
  57.     }

  58. }