/**
  * @file	MatchCount.java
  * @synopsis 	Modification of Match.java to
  *		count number of comparisons.
  *		CONVENTION:
  *		The first index (i=0) of arrays are not used.
  *
  * @author	Chee Yap
  * @date	Apr 25, 2001 (for Basic Algorithms class)
  */

public class MatchCount {

  // Members:
 	char[] P;	// This is pattern
	char[] T;	// This is the text
	int count;	// counts number of comparisons

  // Constructors:

	MatchCount(char[] p, char[] t) {
	  P = p; T = t;
	  count = 0;
	} //

  // Methods:

	/******************************************************
	 THIS IS THE MAIN ROUTINE
	 ******************************************************/
	public int find(int start) {
	  // init:
		int j = start; // text index 
		int k = 1; // pattern index
	  // loop:
		while (j < T.length) {
		  if (k >= P.length) return(j - k + 1);
		  if (T[j] == P[k]) {
		    count++;
		    j++; k++;
		  } else {
		    count++;
		    j = j - k + 2;  k = 1;
		  }
		} // while
	  // not found:
		return(-1);
	} // find()

	/******************************************************
	 prints data
	 ******************************************************/
	void output() {
	  System.out.print("> Pattern = \""); 
	  for (int i=1; i< P.length; i++) 
		System.out.print(P[i]);
	  System.out.print("\"\n> Text    = \""); 
	  for (int i=1; i< T.length; i++) 
		System.out.print(T[i]);
	  System.out.println("\"");
	} // output()


	/******************************************************
	 Main method
	 ******************************************************/
	public static void main( String[] args) {

	  // sample input with 6 keys
	  //	(the first is a dummy key)

	  // char[] p = {'0', 'o', 'u'};
	  char[] p = {'0', 'y', 'o', 'u'};
	  char[] t = {'0',
		'a', 'r', 'e', ' ', 'y', 'o', 'u', ' ',
		'a', ' ', 'y', 'o', 'u', 't', 'h', '?'};

	  // construct a MatchCount object
	  MatchCount m = new MatchCount(p, t);
	  m.output();  	// print data

	  // find all matches
	  int f = m.find(1);
	  if (f<1)
	  	System.out.println(">>  No match found");
	  else {
		while (f>=1) {
		  System.out.println(">>  Match found at position " + f);
		  f = m.find(f+1);
		}//while
	  }//else

	  System.out.println(">>  Number of Comparisons = " + m.count);
  	} // main

}//class MatchCount
