Skip to content

Instantly share code, notes, and snippets.

@larsgroeber
Created October 6, 2017 14:20
Show Gist options
  • Save larsgroeber/5837eb4a990c42098403eed70a57b2e4 to your computer and use it in GitHub Desktop.
Save larsgroeber/5837eb4a990c42098403eed70a57b2e4 to your computer and use it in GitHub Desktop.
Small anagram finder in c++. Generates a hash table from a dictionary file of words.
/**
* \author Lars Gröber
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <thread>
#include <map>
#include <sstream>
#include <algorithm>
#include <numeric>
std::string hash_word ( const std::string& s )
{
std::string hash = "00000000000000000000000000";
for ( char c : s )
{
if ( isalpha( c ) )
{
hash[c - 'a']++;
}
}
return hash;
}
void print_vector ( const std::vector<std::string>& v, const std::string& original = "" )
{
for ( const auto& s : v )
{
if ( s != original )
{
std::cout << s << " ";
}
}
std::cout << std::endl;
}
int main ( int argc, char const* argv[] )
{
if ( argc != 2 )
{
std::cout << "Usage: " << argv[0] << " dic_file\n";
return 0;
}
std::string file_name = argv[1];
std::ifstream file( file_name );
if ( !file.is_open() )
{
std::cout << "Opening file failed!" << '\n';
return -1;
}
std::unordered_map<std::string, std::vector<std::string>> hash_table;
std::cout << "Generating hash table..." << std::flush;
for ( std::string line; std::getline( file, line ); )
{
if (line[line.length() - 1] == '\r')
{
line = line.substr( 0, line.length() - 1 );
}
std::transform( line.begin(), line.end(), line.begin(), ::tolower );
(hash_table[hash_word( line )]).push_back( line );
}
std::cout << "Done\n";
std::cout << "Found " << std::accumulate( hash_table.begin(), hash_table.end(), 0, [] ( int a, auto b )
{
return (b.second.size() > 1) ? a + 1 : a;
} ) << " anagrams\n\n";
std::cout << "Write '\\exit' to exit.\n";
while ( true )
{
std::cout << "Please give a word:\n";
std::string input;
std::getline( std::cin, input );
if ( input == "\\exit" )
{ break; }
std::transform( input.begin(), input.end(), input.begin(), ::tolower );
print_vector( hash_table[hash_word( input )], input );
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment