Jump to content

Array Associativo


aalmeid

Recommended Posts

Boas pessoal, estou a ter dúvidas na parte da teoria de um associativeArray. Alguém me sabe dizer um bom link onde possa encontrar boa informação? Fiz várias pesquisas e nunca encontrei em lado nenhum algo que me retira-se as dúvidas sobre o assunto. Queria saber o que é, para que serve, ... Basicamente, quero aprender da estaca zero o que é

Alguma sugestão de leitura?

Cumps

Link to comment
Share on other sites

Procura no Google por tabelas de dispersão, hash tables, dicionários...

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Link to comment
Share on other sites

Reaproveitando o tópico,

estou a fazer um contador de ocorrência de palavras com um AssociativeArray, mas surgiu-me uma dúvida

       public static void main (String [] args)
{
 if (args.length == 0)
 {
  System.err.println ("Erro nos argumentos");
  System.exit(0);
 }

 AssociativeArray<String> aa = new AssociativeArray<String>(100);

 for (int i = 0; i < args.length; i++)
 {
  try{
   File fin = new File (args[i]);
   Scanner scan = new Scanner(fin);

   if (fin.isDirectory())
   {
   }

   if (!fin.canRead())
   {
   }

   if (!fin.exists())
   {
   }

   String line;

   while (scan.hasNextLine())
   {
    line = scan.nextLine();
    String [] palavras = line.split(" ");

    for (int j = 0; j < palavras.length; j++)
    {
     aa.set(palavras[j],"1");
    }
   }
   scan.close();
  }catch(FileNotFoundException e)
  {
   System.err.println (e);
   System.exit(4);
  }
 }
 /*try{
  //String ficheiro = "histograma.txt";
  //File fout = new File(ficheiro);
  //PrintWriter pwf = new PrintWriter(fout);

  //if !fout.canWrite() ...*/

  int cont = 0;
  String [] keys = aa.keysToArray();

  for (int i = 0; i < keys.length; i++)
  {

   //cont = aa.size();
   System.out.printf ("(%4s,%4s)\n",keys[i],aa.get(keys[i]));
   cont = 0;
  }

 /*}catch (FileNotFoundException e)
 {
  //
 }*/
}
}

Basicamente, ele guarda as palavras como chave do array e está a inserir a String "1" sempre que encontra uma palavra igual. (Não sei se é a melhor forma).

Até aqui nada nenhuma grande dificuldade.

Agora, a minha dificuldade encontra-se na parte de contar o nº de ocorrências. Como poderei fazer isso? A minha classe do array associativo tem apenas as funções

set(key,elem); -> associação;

get(key); -> devolve elemento associado à chave;

delete(key); -> apaga associação

exists(key); -> indica se existe uma chave

isEmpty();

size(); -> nº associações

clear();

keysToArray(); -> devolve array com todas as chaves

Link to comment
Share on other sites

não faço ideia porque não usas a HashTable que te foi dita anteriormente ...

HashTable<String, Integer> palavras = new HashTable<String, Integer>();

   while (scan.hasNextLine())
   {
        line = scan.nextLine();
        String [] pals = line.split(" ");

        for (int j = 0; j < pals.length; j++) {
            if (palavras.containsKey(pals[j]))
               palavras.put(pals[j], palavras.get(pals[j]) + 1);
            else 

               palavras.put(pals[j], 1);
        }
   }

desta forma terás sempre uma associação de palavra<->número de ocorrências

IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.