All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.chocosolver.util.iterators.IntVarValueIterator Maven / Gradle / Ivy

There is a newer version: 4.10.17
Show newest version
/*
 * This file is part of choco-solver, http://choco-solver.org/
 *
 * Copyright (c) 2022, IMT Atlantique. All rights reserved.
 *
 * Licensed under the BSD 4-clause license.
 *
 * See LICENSE file in the project root for full license information.
 */
package org.chocosolver.util.iterators;

import java.util.NoSuchElementException;
import org.chocosolver.solver.variables.IntVar;

import java.util.Iterator;

/**
 * Object to iterate over an IntVar values using
 * 
 *     for(int value:var){
 *         ...
 *     }
 * 
 * that is equivalent to
 * 
 *     int ub = var.getUB();
 *     for(int value = var.getLB(); values <= ub; value = var.nextValue(value)){
 *         ...
 *     }
 * 
 *
 * @author Jean-Guillaume Fages
 */
public class IntVarValueIterator implements Iterator {

	/**
	 * Variable to iterate on
	 */
	private final IntVar var;
    /**
     * current returned value
     */
	private int value;
    /**
     * upper bound of {@link #var}
     */
	private int ub;

	/**
	 * Creates an object to iterate over an IntVar values using
	 * 
	 *     for(int value:var){
	 *         ...
	 *     }
	 * 
	 * that is equivalent to
	 * 
	 *     int ub = var.getUB();
	 *     for(int value = var.getLB(); values <= ub; value = var.nextValue(value)){
	 *         ...
	 *     }
	 * 
	 * @param v an integer variables
	 */
	public IntVarValueIterator(IntVar v){
		this.var = v;
	}

	/**
	 * Reset iteration (to avoid creating a new IntVarValueIterator() for every iteration)
	 * Stores the current upper bound
	 */
	public void reset(){
		value = var.getLB()-1;
		ub = var.getUB();
	}

	@Override
	public boolean hasNext() {
		return var.nextValue(value) <= ub;
	}

	@Override
	public Integer next() {
		value = var.nextValue(value);
		if(value > ub) {
			throw new NoSuchElementException("IntVarValueIterator for IntVar "+var+" has no more element");
		}
		return value;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy