Anagrams: Difference between revisions

1,165 bytes added ,  15 years ago
added c++
(→‎{{header|Haskell}}: correct output)
(added c++)
Line 1:
{{task|Text processing}}
Two or more words can be composed of the same characters, but in a different order. Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them.
 
=={{header|C++}}==
<cpp>#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <iterator>
 
int main() {
std::ifstream in("unixdict.txt");
std::map<std::string, std::vector<std::string> > anagrams;
 
std::string word;
size_t count = 0;
while (std::getline(in, word)) {
std::string key = word;
std::sort(key.begin(), key.end());
// note: the [] operator automatically inserts a new value if key does not exist
anagrams[key].push_back(word);
count = std::max(count, anagrams[key].size());
}
 
in.close();
 
for (std::map<std::string, std::vector<std::string> >::iterator it = anagrams.begin();
it != anagrams.end();
it++)
if (it->second.size() >= count) {
std::copy(it->second.begin(), it->second.end(),
std::ostream_iterator<std::string>(std::cout, ", "));
std::cout << std::endl;
}
return 0;
}</cpp>
Output:
abel, able, bale, bela, elba,
caret, carte, cater, crate, trace,
angel, angle, galen, glean, lange,
alger, glare, lager, large, regal,
elan, lane, lean, lena, neal,
evil, levi, live, veil, vile,
 
== {{header|D}} ==
Anonymous user