How to print all possible permutations (all possible orderings) of the words in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <string>

using std::vector;
using std::string;

void wordsPermutations(vector<string> words, vector<string> current) {
    if (words.empty()) {
        for (int i = 0; i < current.size(); i++)
            std::cout << current[i] << (i + 1 < current.size() ? " " : "");
        std::cout << std::endl;
        return;
    }

    for (int i = 0; i < words.size(); i++) {
        vector<string> remaining = words;
        remaining.erase(remaining.begin() + i);

        vector<string> next = current;
        next.push_back(words[i]);

        wordsPermutations(remaining, next); // Recursive Backtracking
    }
}

int main() {
    vector<string> words = {"word-1", "word-2", "word-3"};
    
    wordsPermutations(words, {});
}


/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // sort, next_permutation

void print_words_permutations(std::vector<std::string> words) {
    std::sort(words.begin(), words.end());

    do {
        for (int i = 0; i < words.size(); i++)
            std::cout << words[i] << (i + 1 < words.size() ? " " : "");
        std::cout << std::endl;
    } while (std::next_permutation(words.begin(), words.end()));
}

int main() {
    std::vector<std::string> words = {"word-1", "word-2", "word-3"};
    
    print_words_permutations(words);
}



/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz
edited Apr 14 by avibootz

Related questions

...