I'm fairly new to C++ programming and am facing quite an issue with writing a method that with create and output all permutations of a list of names that the user inputs. The output works okay with three names input for every other line, but won't hold the first name down. Then with more names added the issue is much worse. I honestly have no idea how to fix this or what even is wrong with it so any help would be much appreciated. Thanks! Code below:
// TODO: Write method to create and output all permutations of the list of names.
void AllPermutations(const vector<string> &permList, const vector<string> &nameList) {
I always think of them like counting in binary.
0000
0001
0010
0011
...
you make loops that change just 1 item per iteration.
so if you have w a s d f g and need 3 of them:
w a s
w a d
w a f
w a g
that is all the w a set.
so have to change the a:
w s d
w s f
w s g
... and so on. after a bit the w changes and you go again. Its just pure iteration, you don't need all that copying and memory abuse (push/pop/erase/ movements and copies).
if you need to KEEP each one instead of print each one, you DO need to store them, but even so all the erase and such seem overkill. I would consider just keeping an index into the original container for each (pointer or array index) rather than copy and store all that data so many times.
these get large moderately quickly, and printing is slow. I would not advise testing 100 names choose 50 or something :P
Well, I do need to print them. Here’s what my output is meant to look like with just three names input:
Julia Lucas Mia
Julia Mia Lucas
Lucas Julia Mia
Lucas Mia Julia
Mia Julia Lucas
Mia Lucas Julia
But here’s what my output looks like instead:
Julia Lucas Mia
Mia Lucas
Lucas Julia Mia
Mia Julia
Mia Julia Lucas
Lucas Julia
So I more so mean it’s not printing out that first name again on the second loop for the output, if that makes sense? It gets even worse when the input is more names, each line out output dropping a name practically unless it is that initial loop for each group.
A brute force solution with minimal effort applied, but showing that you only need iteration:
if you get more than 6 names you will want to rewrite it more intelligently. (and if you change the number you have to fix the hard coded parts... its just a silly example ).
Julia Lucas Mia Timmy
Julia Lucas Timmy Mia
Julia Mia Lucas Timmy
Julia Mia Timmy Lucas
Julia Timmy Lucas Mia
Julia Timmy Mia Lucas
Lucas Julia Mia Timmy
Lucas Julia Timmy Mia
Lucas Mia Julia Timmy
Lucas Mia Timmy Julia
Lucas Timmy Julia Mia
Lucas Timmy Mia Julia
Mia Julia Lucas Timmy
Mia Julia Timmy Lucas
Mia Lucas Julia Timmy
Mia Lucas Timmy Julia
Mia Timmy Julia Lucas
Mia Timmy Lucas Julia
Timmy Julia Lucas Mia
Timmy Julia Mia Lucas
Timmy Lucas Julia Mia
Timmy Lucas Mia Julia
Timmy Mia Julia Lucas
Timmy Mia Lucas Julia