permutation of 2 strings

Hi
I want to write a program that gives 2 strings(char type) and combine them in different ways.
for example if 2 strings are "abc" and "mn" the program should print :
abcmn abmnc amnbc mnabc mabcn mannbc mabnc ambnc ambcn abmcn
as you see they should be in ordered form in each string. I mean that for example "c" couldn't be before "a" or "n" couldn't be before "m"
what can I do?
Nested loops is one possibility.

'm' can be inserted in four positions: 1a2b3c4
For each case, 'n' can be inserted after 'm' or any charater that will be after the 'm'.
Thus, when 'm' is in position 1, 'n' has 4 possibilities.
When 'm' is in position 2, 'n' has 3 possibilities.
...
In c++:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string>
#include <algorithm>
#include <initializer_list>

class allPerm
{
	bool nextperm;
	std::string full;
	
	bool next()
	{
		if (this->nextperm)
			this->nextperm = std::next_permutation(this->full.begin(), this->full.end());
		return this->nextperm;
	}
	
	public:
	explicit allPerm(const std::initializer_list<std::string> &strings)
	: nextperm(true)
	{
		for (auto s : strings)
			this->full.append(s);
		std::sort(full.begin(), full.end());
	}
	
	operator bool()
	{
		return nextperm;
	}
	
	std::string gen()
	{
		if (this->next())
			return full;
		return "";
	}
};
	

int main() 
{
	std::string a = "abc", b = "mn";
	allPerm permute({a, b});
	
	while(permute)
		std::cout << permute.gen() << " ";
	return 0;
}



In python:

1
2
3
4
5
6
7
8
9
10
>>> from itertools import permutations
>>> def all_perm(*args):
...     s = ''.join(sorted(args))
...     for cbn in permutations(s):
...             yield ''.join(cbn)
... 
>>> 
>>> for word in all_perm('abc', 'mn'):
...     print word,
... 


OutPut:

abcmn abcnm abmcn abmnc abncm abnmc acbmn acbnm acmbn acmnb acnbm 
acnmb ambcn ambnc amcbn amcnb amnbc amncb anbcm anbmc ancbm ancmb 
anmbc anmcb bacmn bacnm bamcn bamnc bancm banmc bcamn bcanm bcman 
bcmna bcnam bcnma bmacn bmanc bmcan bmcna bmnac bmnca bnacm bnamc 
bncam bncma bnmac bnmca cabmn cabnm cambn camnb canbm canmb cbamn 
cbanm cbman cbmna cbnam cbnma cmabn cmanb cmban cmbna cmnab cmnba 
cnabm cnamb cnbam cnbma cnmab cnmba mabcn mabnc macbn macnb manbc 
mancb mbacn mbanc mbcan mbcna mbnac mbnca mcabn mcanb mcban mcbna 
mcnab mcnba mnabc mnacb mnbac mnbca mncab mncba nabcm nabmc nacbm 
nacmb nambc namcb nbacm nbamc nbcam nbcma nbmac nbmca ncabm ncamb 
ncbam ncbma ncmab ncmba nmabc nmacb nmbac nmbca nmcab nmcba
Last edited on
Topic archived. No new replies allowed.