Last active
August 29, 2015 14:11
-
-
Save cengiz-io/62818cb0a2767a9f2b7e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <fstream> | |
#include <stdlib.h> | |
#include <iterator> | |
#include <vector> | |
#include <set> | |
using namespace std; | |
void permutate(const unsigned int length, | |
const string& word, | |
vector<int>& index, | |
size_t depth, | |
set<string>& words) | |
{ | |
if (length == 1) { | |
for (size_t i = 0; i < word.length(); ++i) { | |
words.insert(string(1, word[i])); | |
} | |
return; | |
} | |
if (depth >= length) { | |
string permutation; | |
for (size_t i = 0; i < length; ++i) { | |
permutation.push_back(word[index[i]]); | |
} | |
words.insert(permutation); | |
return; | |
} | |
for (size_t i = 0; i < word.length(); ++i) { | |
index[depth] = static_cast<int>(i); | |
permutate(length, word, index, depth + 1, words); | |
} | |
} | |
int main(int argc, char *argv[]) { | |
if (argc < 2) return -1; | |
ifstream datafile(argv[1]); | |
string line; | |
while (getline(datafile, line)) { | |
if (line.length() < 1) continue; | |
int separator_index = line.find_first_of(","); | |
unsigned int length_as_int; | |
size_t length = 0; | |
string letters = ""; | |
istringstream length_part(line.substr(0, separator_index)); | |
length_part >> length_as_int; | |
length = static_cast<size_t>(length_as_int); | |
letters = line.substr(separator_index + 1, line.length()); | |
vector<int> index(length); | |
ostringstream out; | |
set<string> words; | |
permutate(length, letters, index, 0, words); | |
copy( | |
words.begin(), | |
words.end(), | |
ostream_iterator<string>(out, ",") | |
); | |
string output = out.str(); | |
output.resize(output.length() - 1); | |
cout << output << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment