Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created November 29, 2016 16:08
Show Gist options
  • Save davepkennedy/382b467800cf2d30f34335bd51821861 to your computer and use it in GitHub Desktop.
Save davepkennedy/382b467800cf2d30f34335bd51821861 to your computer and use it in GitHub Desktop.
Anagrams in C++
//
// main.cpp
// anagrammer
//
// Created by Dave Kennedy on 29/11/2016.
// Copyright © 2016 Dave Kennedy. All rights reserved.
//
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
vector <string> vary (char c, const string& word) {
vector<string> variations;
string to_insert (&c, 1);
for (size_t pos = 0; pos <= word.length(); pos++) {
string temp_word = word;
temp_word.insert(pos, to_insert);
variations.push_back(temp_word);
}
return variations;
}
vector <string> anagram (const string& word) {
vector <string> anagrams;
vector <string> intermediates;
stack <char> chars;
for_each(word.begin(), word.end(), [&](char c){chars.push(c);});
intermediates.push_back ("");
while (chars.size() > 0) {
anagrams.clear();
char c = chars.top();
chars.pop();
for (auto word : intermediates) {
vector<string> variations = vary (c, word);
anagrams.insert(anagrams.end(), variations.begin(), variations.end());
}
intermediates = anagrams;
}
return anagrams;
}
int main(int argc, const char * argv[]) {
// insert code here...
for (auto word : anagram("abc")) {
cout << word << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment