
/*
 * Instituto Superior de Engenharia do Porto
 *
 * Estruturas de Informação
 *
 * 2000/2001
 *
 * ------------------------------------------
 *
 * Classe de Tabela de Hashing fechado para strings
 *
 * hash_ab_str.cpp
 *
 */

#include "hasha_str.h"


void HashTableStrings :: copia( const HashTableStrings& o )
{
	m_tabela = o.m_tabela;
}


HashTableStrings :: HashTableStrings( int nSize /* = DIM_NORMAL */ )
{
	m_tabela.resize( nSize );
}


HashTableStrings::HashTableStrings( const HashTableStrings& o )
{
	copia( o );
}


bool HashTableStrings::insere( const string& sTexto )
{
	int pos   = HashingStrings( sTexto, m_tabela.size() );
	int index = pos;

	do
	{
		if ( m_tabela[index] == "" )
		{
			m_tabela[index] = sTexto;
			return true;
		}
		if ( ++index >= m_tabela.size() ) index = 0;
	}
	while ( index != pos );
	
	return false;
}


bool HashTableStrings :: pesquisa( const string& sTexto )
{
	int pos   = HashingStrings( sTexto, m_tabela.size() );
	int index = pos;

	do
	{
		if ( m_tabela[index] == sTexto ) return true;
		//if ( m_tabela[index] == "" ) return false;
		if ( ++index >= m_tabela.size() ) index = 0;
	}
	while ( index != pos );

	return false;
}


bool HashTableStrings :: elimina( const string& sTexto )
{
	int pos = HashingStrings( sTexto, m_tabela.size() );
	int index = pos;

	do
	{
		if ( m_tabela[index] == sTexto ) 
		{
			m_tabela[index] = "";
			return true;
		}
		if ( ++index >= m_tabela.size() ) index = 0;
	}
	while ( index != pos );

	return false;
}


HashTableStrings& HashTableStrings :: operator=( const HashTableStrings& o )
{
	copia( o );
	return *this;
}


int HashingStrings( string sTexto, int nDiv /* = -1 */)
{
	int accum = 0;

	for(int i = 0; i < sTexto.length(); i++) accum += sTexto[i];
	if ( nDiv == -1 )
		return accum;
	else
		return accum % nDiv;
}
