/***********************************************************
 * A Simulation of a Liquid-Based Natural Algorithm for
 * Finding the Average of n Integers Using a Cellular
 * Automaton
 *
 * by Dominik Schultes
 * 8. April 2004
 *
 * Designed for Linux 2.4.19 and the g++ compiler 3.2.
 * At least the method "clrscr" has to be adapted if
 * Windows is used !
 ***********************************************************/


#include <algorithm>
#include <iostream>

using namespace std;


/**
   Clears the screen. This method is platform-dependent !
   It has to be adapted if Windows instead of Linux is used.
*/
void clrscr() {
    system("clear");
}


/**
   This class encapsulates the Cellular Automaton (CA)
   that is used to determine the average of several
   integers.
*/
class AverageCA
{
 private:
    // The possible states of each cell
    static const int OUT_OF_BOUNDS = 0;
    static const int EMPTY = 1;
    static const int RIGHT = 2;
    static const int LEFT = 3;
    static const int RIGHT_TLB = 4;
    static const int LEFT_TRB = 5;

    /**
       This class encapsulates the cells of the automaton.
    */
    class Cells {
     public:
	Cells() {}

	/**
	   Create a two-dimensional array of integers,
	   where each integer represents the state of
	   the corresponding cell.
	*/
	Cells(int n, int m) : _n( n ), _m( m ) {
	    _cells = new int[n * m];	    
	}

	~Cells() {
	    delete[] _cells;
	}

	/** Returns the state of the specified cell. */
	int getState(int x, int y) {
	    if ((x < 0) || (x >= _n) || (y < 0) || (y >= _m))
		return OUT_OF_BOUNDS;
	    
	    return _cells[ x*_m + y ];
	}
	
	/** Sets the state of the specified cell. */
	void setState(int x, int y, int newState) {
	    _cells[ x*_m + y ] = newState;
	}
	    
     private:
	int _n; // the number of integers
	int _m; // the value of the biggest integer
	
	// a two-dim. array that represents the cells
	int* _cells; 
    };
    
 public:
    /** Creates and initializes the Cellular Automaton. */
    AverageCA(int n, int input[])
	: _n( n ), _clocks( 0 ), _changed( 0 ) {
	// determine the maximum integer, compute the sum
	// of all integers, and compute the desired value
	// (the average of all integers) (in order to be
	// able to check the result)
	_max = 0;
	int sum = 0;
	for (int i=0; i<n; i++) {
	    _max = max(_max, input[i]);
	    sum += input[i];
	}
	_desiredValue = sum / (float)n;

	// create the cells
	_cells = new Cells(n, _max);

	// initialize the states of the cells
	for (int x=0; x<n; x++) {
	    for (int y=0; y<input[x]; y++)
		setState(x,y,RIGHT);
	    for (int y=input[x]; y<_max; y++)
		setState(x,y,EMPTY);
	}
    }

    ~AverageCA() {
	delete _cells;
    }

    /**
       Returns true, iff no cells changed during the last
       step.
    */
    bool isFinished() {
	return (_changed == 0);
    }

    /**
       Returns the average of all integers, which has been
       computed with conventional means.
    */
    float getDesiredValue() {
	return _desiredValue;
    }

    /**
       Returns the average of all integers, which has been
       computed by the Cellular Automaton.
    */
    float getActualValue() {
	return getNoOfCompletedRows() +
	    (getNoOfNonEmptyCellsOnFirstUncompletedRow() /
	     (float)(_n));
    }

    /** Print the current state of the CA. */
    void printCells() {
	clrscr();
	for (int y=_max-1; y>=0; y--) {
	    for (int x=0; x<_n; x++) {
		switch( getState(x,y) ) {
		    case EMPTY:
			cout << " "; break;
		    case RIGHT:
			cout << "r"; break;
		    case LEFT:
			cout << "l"; break;
		    case RIGHT_TLB:
			cout << "R"; break;
		    case LEFT_TRB:
			cout << "L"; break;
		}
	    }
	    cout << endl;
	}
    }

    /** Print some statistics. */
    void printStatistics() {
	cout << endl;
	cout << "n = " << _n << " ; max = " << _max
	     << " ; no of clocks = " << _clocks << endl;

	int sum = 0;
	for (int y=0; y<_max; y++) {
	    for (int x=0; x<_n; x++)
		if (getState(x,y) != EMPTY) sum++;
	}

	float average = sum / (float)_n;
	
	int noOfCompletedRows = getNoOfCompletedRows();

	int itemsOnFirstUncompletedRow =
	    getNoOfNonEmptyCellsOnFirstUncompletedRow();

	int itemsInFinalState = 0;
	for (int y=0; y<_max; y++) {
	    for (int x=0; x<_n; x++)
		if (getState(x,y) == RIGHT_TLB) itemsInFinalState++;
	}

	cout << "sum = " << sum << " ; average = "
	     << average << endl
	     << "no of completed rows = "
	     << noOfCompletedRows
	     << " ; no of non-empty cells on the first "
	     << "uncompleted row = k = "
	     << itemsOnFirstUncompletedRow
	     << " ; k / n = "
	     << (itemsOnFirstUncompletedRow / (float)_n)
	     << endl
	     << "percentage of cells in final state = "
	     << (itemsInFinalState / (float)sum * 100)
	     << " % ; "
	     << _changed << " cells changed" << endl;
    }

    /** Execute one step. */
    void clock() {
	_clocks++;
	// execute all substeps in the appropriate order
	subClock1();
	subClock2();
	subClock3();
	subClock4();
	subClock5();
	cleanUp();
    }

 private:
    /** Returns the state of the specified cell. */
    int getState(int x, int y) {
	return _cells->getState(x,y);
    }
    
    /** Sets the state of the specified cell. */
    void setState(int x, int y, int newState) {
	_cells->setState(x,y,newState);
    }

    /** Substep according to Rule 1 (down). */
    void subClock1() {
	Cells *cellsNew = new Cells(_n,_max);
	for (int x=0; x<_n; x++) {
	    for (int y=0; y<_max; y++) {
		cellsNew->setState(x,y,getState(x,y));
		if (getState(x,y) == EMPTY) {
		    if (getState(x,y+1) > EMPTY)
			cellsNew->setState(x,y,-RIGHT);
		}
		if (getState(x,y) > EMPTY) {
		    if (getState(x,y-1) == EMPTY)
			cellsNew->setState(x,y,-EMPTY);
		}
	    }
	}
	delete _cells;
	_cells = cellsNew;
    }

    /** Substep according to Rule 2 (down-right). */
    void subClock2() {
	Cells *cellsNew = new Cells(_n,_max);
	for (int x=0; x<_n; x++) {
	    for (int y=0; y<_max; y++) {
		cellsNew->setState(x,y,getState(x,y));
		if (getState(x,y) == EMPTY) {
		    if (getState(x-1,y+1) > EMPTY)
			cellsNew->setState(x,y,-RIGHT);
		}
		if (getState(x,y) > EMPTY) {
		    if (getState(x+1,y-1) == EMPTY)
			cellsNew->setState(x,y,-EMPTY);
		}
	    }
	}
	delete _cells;
	_cells = cellsNew;
    }

    /** Substep according to Rule 3 (down-left). */
    void subClock3() {
	Cells *cellsNew = new Cells(_n,_max);
	for (int x=0; x<_n; x++) {
	    for (int y=0; y<_max; y++) {
		cellsNew->setState(x,y,getState(x,y));
		if (getState(x,y) == EMPTY) {
		    if (getState(x+1,y+1) > EMPTY)
			cellsNew->setState(x,y,-RIGHT);
		}
		if (getState(x,y) > EMPTY) {
		    if (getState(x-1,y-1) == EMPTY)
			cellsNew->setState(x,y,-EMPTY);
		}
	    }
	}
	delete _cells;
	_cells = cellsNew;
    }

    /** Substep according to Rule 4 (right). */
    void subClock4() {
	Cells *cellsNew = new Cells(_n,_max);
	for (int x=0; x<_n; x++) {
	    for (int y=0; y<_max; y++) {
		int currentState = getState(x,y);
		cellsNew->setState(x,y,currentState);
		if (currentState == EMPTY) {
		    int leftState = getState(x-1,y);
		    if ((leftState == RIGHT) ||
			(leftState == RIGHT_TLB))
			cellsNew->setState(x,y,-leftState);
		}
		int rightState = getState(x+1,y);
		if (currentState == RIGHT) {
		    if (rightState >= EMPTY)
			cellsNew->setState(x,y,-rightState);
		    else if (rightState == OUT_OF_BOUNDS)
			cellsNew->setState(x,y,-LEFT_TRB);
		}
		if (currentState == RIGHT_TLB) {
		    if (rightState == EMPTY)
			cellsNew->setState(x,y,-EMPTY);
		}
	    }
	}
	delete _cells;
	_cells = cellsNew;	
    }

    /** Substep according to Rule 5 (left). */
    void subClock5() {
	Cells *cellsNew = new Cells(_n,_max);
	for (int x=0; x<_n; x++) {
	    for (int y=0; y<_max; y++) {
		int currentState = getState(x,y);
		cellsNew->setState(x,y,currentState);
		if (currentState == EMPTY) {
		    int rightState = getState(x+1,y);
		    if ((rightState == LEFT) ||
			(rightState == LEFT_TRB))
			cellsNew->setState(x,y,-rightState);
		}
		int leftState = getState(x-1,y);
		if (currentState == LEFT) {
		    if (leftState >= EMPTY)
			cellsNew->setState(x,y,-leftState);
		    else if (leftState == OUT_OF_BOUNDS)
			cellsNew->setState(x,y,-RIGHT_TLB);
		}
		if (currentState == LEFT_TRB) {
		    if (leftState == EMPTY)
			cellsNew->setState(x,y,-EMPTY);
		    else if ((leftState == OUT_OF_BOUNDS) ||
			     (leftState == RIGHT_TLB))
			cellsNew->setState(x,y,-RIGHT_TLB);
		    else cellsNew->setState(x,y,-LEFT_TRB);
		}
	    }
	}
	delete _cells;
	_cells = cellsNew;
    }

    /** Reset the markers. */
    void cleanUp() {
	_changed = 0;
	for (int x=0; x<_n; x++) {
	    for (int y=0; y<_max; y++) {
		if (getState(x,y) < 0) {
		    _changed++;
		    setState(x,y,abs(getState(x,y)));
		}
	    }
	}
    }

    /** Returns the number of completely filled rows. */
    int getNoOfCompletedRows() {
	int noOfCompletedRows = 0;
	for (int y=0; y<_max; y++) {
	    bool complete = true;
	    for (int x=0; x<_n; x++)
		if (getState(x,y) == EMPTY)
		    complete = false;
	    if (complete) noOfCompletedRows++;
	    else break;
	}
	return noOfCompletedRows;
    }

    /**
       Returns the number of non-empty cells on the first
       uncompleted row.
    */
    int getNoOfNonEmptyCellsOnFirstUncompletedRow() {
	int noOfCompletedRows = getNoOfCompletedRows();
	int itemsOnFirstUncompletedRow = 0;
	if (noOfCompletedRows < _max) {
	    for (int x=0; x<_n; x++)
		if (getState(x,noOfCompletedRows) != EMPTY)
		    itemsOnFirstUncompletedRow++;
	}
	return itemsOnFirstUncompletedRow;
    }
    
    
    int _n; // the number of integers
    int _max; // the maximum integer
    int _clocks; // the number of already executed steps
    
    // the number of cells whose state has changed during
    // the last step
    int _changed; 
    float _desiredValue; // the average of all integers

    Cells *_cells; // the cells of this automaton
};


/**
   Runs a randomly generated test case automatically and
   checks the result.
*/
void runAutomaticly() {
    int n = 120; int m = 100;

    int input[n];
    for (int i=0; i<n; i++) {
	input[i] = (int)(rand() /
			 (double)(RAND_MAX+1.0) * m);
    }

    AverageCA* ca = new AverageCA(n, input);

    char ch;
    //ca->printCells();
    //ca->printStatistics();
    //cin.get(ch);
    do {
	ca->clock();
	//clrscr();
	//ca->printStatistics();
    } while ( ! ca->isFinished());
    
    //ca->printCells();
    //ca->printStatistics();
    cout << "DESIRED VALUE = " << ca->getDesiredValue()
	 << " ; ACTUAL VALUE = " << ca->getActualValue()
	 << endl;
    if (abs(ca->getDesiredValue() -
	    ca->getActualValue()) > 0.00001) {
	cout << "ERROR !!!" << endl;
	exit(-1);
    }
    else {
	cout << "OKAY" << endl;
    }
    //cin.get(ch);
    
    delete ca;
}


/**
   Runs a randomly generated test case.
   After each step the user has to press RETURN.
*/
void runManually(int n, int m) {
    int input[n];
    for (int i=0; i<n; i++) {
	input[i] = (int)(rand() /
			 (double)(RAND_MAX+1.0) * m);
    }

    AverageCA* ca = new AverageCA(n, input);

    char ch;
    ca->printCells();
    ca->printStatistics();
    cout << "(Press RETURN to go on or enter \"q\" and "
	 << "press RETURN to quit.)" << endl;
    cin.get(ch);
    while(ch != 'q') {
	ca->clock();	
	ca->printCells();
	ca->printStatistics();
	cout << "(Press RETURN to go on or enter \"q\" and "
	     << "press RETURN to quit.)" << endl;	
	cin.get(ch);
    } 
    delete ca;
}

/** The main method. */
int main() {
    // specify here the number of integers n
    // and the maximum value of the integers m
    int n = 30; int m = 11;

    runManually(n,m);

    
    return 0;
}
