/**
 * MerchantSelector.java
 * Theodoros Lappas
 * http://www.cs.ucr.edu/~tlappas/
 */
package solver;

import java.util.Vector;

public class MerchantSelector {

	private float[] finalRow;
	private float revenueTable[][][];

	private int backTrackingTable[][][];

	private int couponCapacity;
	private int marketLimit;
	private int merchantsInMarket;

	public float[] getFinalRow() {
		return finalRow;
	}

	public MerchantSelector(int merchantNum, int maxDealsPerMarket, int capacity)
			throws Exception {
		couponCapacity = capacity;
		marketLimit = maxDealsPerMarket;
		merchantsInMarket = merchantNum;
		revenueTable = new float[merchantNum + 1][capacity + 1][maxDealsPerMarket + 1];
		backTrackingTable = new int[merchantNum + 1][capacity + 1][maxDealsPerMarket + 1];
		finalRow = new float[capacity + 1];
	}

	public void run(int merNum, Vector<Deal> deals) {

		merchantsInMarket = merNum;

		// variables for the two options evaluated at each step of the recursion
		float val1, val2;

		// for each merchant
		for (int merchant = 1; merchant < merchantsInMarket + 1; ++merchant) {

			// for each allowed market unit
			for (int k = 1; k < marketLimit + 1; ++k) {

				// for each available coupon
				for (int c = 1; c < couponCapacity + 1; ++c) {

					if (c >= deals.get(merchant).coupons) {// still within
															// capacity

						val1 = revenueTable[merchant - 1][c][k]; // dont pick
																	// merchant
						// // m
						val2 = revenueTable[merchant - 1][c
								- deals.get(merchant).coupons][k - 1]
								+ deals.get(merchant).benefit; // pick merchant
																// m

						if (val1 >= val2) {
							revenueTable[merchant][c][k] = val1;
							backTrackingTable[merchant][c][k] = 0;
						} else {
							revenueTable[merchant][c][k] = val2;
							backTrackingTable[merchant][c][k] = deals
									.get(merchant).coupons;
						}

					} else {
						revenueTable[merchant][c][k] = revenueTable[merchant - 1][c][k];
						backTrackingTable[merchant][c][k] = 0;
					}
				}
			}
		}

		// populate the final row
		for (int i = 0; i < couponCapacity + 1; ++i) {
			finalRow[i] = revenueTable[merchantsInMarket][i][marketLimit];
		}
	}

	public int[][][] getBackTrackingTable() {
		return backTrackingTable;
	}

	public void setBackTrackingTable(int[][][] backTrackingTable) {
		this.backTrackingTable = backTrackingTable;
	}

}