Note that there are some explanatory texts on larger screens.

plurals
  1. POFind 'connected components' in graph
    text
    copied!<p>I'm building a thesaurus using a <code>HashMap &lt;String,ArrayList&lt;String&gt;&gt;</code> to hold words and their synonyms (this data structure is required).</p> <p>For the purpose of the assignment, the synonymity relation is considered transitive. (We can imagine the thesaurus as a graph). What I'm trying to accomplish is to print this graph in a text file, with a connected component on each line. In other words, all the words that can be pooled together as synonyms should go on a single line.</p> <pre><code>public void save() { try { FileWriter fw = new FileWriter(defaultDefinitionFile); BufferedWriter out = new BufferedWriter(fw); Set&lt;String&gt; keys = thesaurus.keySet(); Iterator&lt;String&gt; ite = keys.iterator(); while (ite.hasNext()) { String key = ite.next(); out.write(key); ArrayList&lt;String&gt; synonyms = thesaurus.get(key); Iterator&lt;String&gt; i = synonyms.iterator(); while (i.hasNext()) { String syn = i.next(); out.write(","+syn); keys.remove(syn); } out.write("\r\n"); } out.close(); fw.close(); } catch (Exception e) { System.out.println("Error writing to file"); e.printStackTrace(); } } </code></pre> <p>This is how I pictured it to happen:</p> <p>Print a word along with each of its synonyms, then remove those synonyms from the data structure so we don't have duplicate lines.</p> <p>Problem is of course that I can't delete anything while i'm iterating over the content of the hashmap.</p> <p>Any alternative approaches I'm missing?</p> <p>P.S. I'm keeping the 'graph' metaphor throughout only because i needed the title to be eloquent and succint. I understand that this metaphor is limited in usefulness.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload