001package org.cpsolver.ifs.model;
002
003/**
004 * Binary constraint. <br>
005 * <br>
006 * Extension of {@link Constraint} that links exactly two variables.
007 * 
008 * @see Variable
009 * @see Constraint
010 * @see Model
011 * 
012 * @version IFS 1.3 (Iterative Forward Search)<br>
013 *          Copyright (C) 2006 - 2014 Tomáš Müller<br>
014 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
015 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
016 * <br>
017 *          This library is free software; you can redistribute it and/or modify
018 *          it under the terms of the GNU Lesser General Public License as
019 *          published by the Free Software Foundation; either version 3 of the
020 *          License, or (at your option) any later version. <br>
021 * <br>
022 *          This library is distributed in the hope that it will be useful, but
023 *          WITHOUT ANY WARRANTY; without even the implied warranty of
024 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
025 *          Lesser General Public License for more details. <br>
026 * <br>
027 *          You should have received a copy of the GNU Lesser General Public
028 *          License along with this library; if not see
029 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
030 * @param <V> Variable
031 * @param <T> Value
032 */
033
034public abstract class BinaryConstraint<V extends Variable<V, T>, T extends Value<V, T>> extends Constraint<V, T> {
035    private V iFirst = null, iSecond = null;
036
037    public BinaryConstraint() {
038        super();
039    }
040
041    @Override
042    public void addVariable(V var) {
043        if (iFirst == null)
044            iFirst = var;
045        else
046            iSecond = var;
047        super.addVariable(var);
048    }
049
050    /** First variable 
051     * @return first variable of the constraint 
052     **/
053    public V first() {
054        return iFirst;
055    }
056
057    /** Second variable 
058     * @return second variable of the constraint 
059     **/
060    public V second() {
061        return iSecond;
062    }
063
064    /** True, id the given variable is the first one 
065     * @param variable given variable
066     * @return true if the given variable is the first variable of the constraint
067     **/
068    public boolean isFirst(V variable) {
069        return variable.equals(first());
070    }
071
072    /**
073     * Returns the variable out of the constraints variables which is different
074     * from the given variable.
075     * @param variable given variable
076     * @return the other variable of the constraint
077     */
078    public V another(V variable) {
079        return (first() != null && variable.equals(first()) ? second() : first());
080    }
081}