I am trying to create a program that looks through all the permutations of a string and then prints out all the valid words. I can get all the permutations, but checking if a word is in a dictionary text files takes around 3 seconds. When I tried 7 letters it took 47:19. Is there any way to read from a file faster?
Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
bool in(std::string arr, char element)
{
for (int i = 0; i < arr.size(); i++)
{
if (arr[i] == element)
{
return true;
}
}
return false;
}
bool inDictionary(std::string str)
{
std::ifstream dictionary;
dictionary.open("words.txt");
if (dictionary.is_open())
{
std::string word;
while (std::getline(dictionary, word))
{
if (word == str)
{
return true;
}
}
}
return false;
}
std::string remainingCharacters(std::string orginal, std::string newString)
{
std::string characters = "";
for (int i = 0; i < orginal.size(); i++)
{
if (!in(newString, orginal[i]))
{
characters += orginal[i];
}
}
return characters;
}
void combinations(std::string cur, std::string original, std::vector<std::string>& permutations)
{
for (int i = 0; i < remainingCharacters(original, cur).size(); i++)
{
permutations.push_back(cur + remainingCharacters(original, cur)[i]);
combinations(cur + remainingCharacters(original, cur)[i], original, permutations);
}
}
int main()
{
std::vector<std::string> permutations;
combinations("", "wdsrock", permutations);
for (int i = 0; i < permutations.size(); i++)
{
if (inDictionary(permutations[i]))
{
std::cout << permutations[i] << ", ";
}
}
;
}