473,805 Members | 2,270 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to generate all possible permutations with repetitions?

Hello,

I need help with an algoritm that given a set of "n" distinct
numbers will
generate all the possible permutations of fixed length "m" of these
numbers WITH repetitions (a total of n^m possibilities). For example:

given the set {1, 2} would output: 111,112,121,122 ,211,212,221,22 2 if
we fix m=3.

What I could do so far is an iterative algorithm which could be used
only if we know before runnin the program "m" and "n" which is not
often the case :)

int n=2; //stores the numebr of elements in the set
int m=3; //stores the length of the desired permutation
char s[] = "12"; //stores our set of numbers
char s1[] = new char[m]; //will store every permutation generated (of
length 3)
int i, j, k; // loop variables

for (i=0; i<length(s); i++) { // first loop
for (j=0; j<length(s); j++) { // second loop
for (k=0; k<length(s); k++) { // third loop
// this code is executed 2^3=8 times
s1[0] = s[i];
s1[1] = s[j];
s1[2] = s[k];
printf("%s\n", s1); // print the permutation
}
}
}
How can I generalize this for any m and n? I suppose some sort of a
recursive algorithm should be used (I don't believe this can be done
by simply iterating). Unfortunately I don't feel much confortable with
recursion. In fact what I am looking for is what would be the
recursive version of the following multiple loops algorithm:

for (i=0;i<n;i++)
for (j=0;j<n;j++)
for (k=0;k<n;k++)
for (l=0;l<n;l++)
etc... (m times)
// Do something here
}
}
}
}
Could you help me with some pseudo code please? And please appologize
me if the term "permutatio n" that I used here is not correct.

Thanks,
Darin
Nov 14 '05 #1
4 8205


darin dimitrov wrote:
Hello,

I need help with an algoritm that given a set of "n" distinct
numbers will
generate all the possible permutations of fixed length "m" of these
numbers WITH repetitions (a total of n^m possibilities). For example:

given the set {1, 2} would output: 111,112,121,122 ,211,212,221,22 2 if
we fix m=3.

What I could do so far is an iterative algorithm which could be used
only if we know before runnin the program "m" and "n" which is not
often the case :)

int n=2; //stores the numebr of elements in the set
int m=3; //stores the length of the desired permutation
char s[] = "12"; //stores our set of numbers
char s1[] = new char[m]; //will store every permutation generated (of new is C++, not C: Use malloc() length 3)
int i, j, k; // loop variables

for (i=0; i<length(s); i++) { // first loop
for (j=0; j<length(s); j++) { // second loop
for (k=0; k<length(s); k++) { // third loop
// this code is executed 2^3=8 times
s1[0] = s[i];
s1[1] = s[j];
s1[2] = s[k];
printf("%s\n", s1); // print the permutation
}
}
} Your C++ code lacks a delete s1 here, in C: a free() call.
How can I generalize this for any m and n? I suppose some sort of a
recursive algorithm should be used (I don't believe this can be done
by simply iterating). Unfortunately I don't feel much confortable with
recursion. In fact what I am looking for is what would be the
recursive version of the following multiple loops algorithm:

for (i=0;i<n;i++)
for (j=0;j<n;j++)
for (k=0;k<n;k++)
for (l=0;l<n;l++)
etc... (m times)
// Do something here
}
}
}
}
Could you help me with some pseudo code please? And please appologize
me if the term "permutatio n" that I used here is not correct.


You need a depth counter to find out in which "loop" you are,
then you run the respective loop.
Try this:

#include <stdio.h> /* puts, fputs; stderr, stdout */
#include <stdlib.h> /* malloc, exit */
#include <string.h> /* strlen */

void permutate_n_plu s (char *str, size_t n, const size_t maxdepth,
const char *baseset, const size_t numbase)
{
size_t i;
char *currpos = &str[n-1];
const char *currchar = baseset;

if (n<maxdepth) { /* We are in an outer loop */
/* run through the baseset for the current depth,
** call permutate_n_plu s() for greater depths */
for (i=0; i<numbase; i++) {
*currpos = *currchar++;
permutate_n_plu s(str, n+1, maxdepth, baseset, numbase);
}
}
else { /* We are in the innermost (output) loop */
/* run through the baseset for the current depth,
** write out the result */
for (i=0; i<numbase; i++) {
*currpos = *currchar++;
fputs(str, stdout);

/* Uncomment this for immediate output
fflush(stdout);
*/
}

}
}

int main (int argc, char **argv)
{
char *string, *baseset;
size_t maxdepth;
unsigned long tmp;

if (argc!=3) {
puts("Usage:\n\ t<program> baseset width");
exit(EXIT_SUCCE SS);
}

baseset = argv[1];
if ( (tmp = strtoul(argv[2],NULL,10)) == 0 )
exit(EXIT_SUCCE SS);

if ( (maxdepth = (size_t) tmp) != tmp ) {
fputs("width too large", stderr);
exit(EXIT_FAILU RE);
}

if ( (string = malloc(maxdepth + 2)) == NULL ) {
fputs("cannot allocate memory for output string", stderr);
exit(EXIT_FAILU RE);
}

/* insert separator and terminate string */
string[maxdepth] = '\t';
string[maxdepth+1] = '\0';

permutate_n_plu s(string, 1, maxdepth, baseset, strlen(baseset) );
puts("");

free(string);
exit(EXIT_SUCCE SS);
}

-------
BTW: You do not need recursion. If the overall number of runs through
the second-to-innermost loop is less than ULONG_MAX, you can use one
loop index to designate the position to be changed.
Another way is creating an array of depth counters each of which runs
through the number of different characters just in the way it would
happen when you were using the recursive call. And so on... :-)
Cheers
Michael
--
E-Mail: Mine is a gmx dot de address.

Nov 14 '05 #2
"darin dimitrov" <da************ @hotmail.com> wrote in message
news:2b******** *************** ***@posting.goo gle.com...
I need help with an algoritm that given a set of "n" distinct
numbers will
generate all the possible permutations of fixed length "m" of these
numbers WITH repetitions (a total of n^m possibilities). For example:

given the set {1, 2} would output: 111,112,121,122 ,211,212,221,22 2 if
we fix m=3. [snip code that wasn't quite C anyway] How can I generalize this for any m and n? I suppose some sort of a
recursive algorithm should be used (I don't believe this can be done
by simply iterating).


#include <stdio.h>
#include <stdlib.h>

int main(void) {
int i, n, m;
int *a;
char s[] = "12";

n = sizeof s - 1;
m = 3;

a = malloc(m * sizeof *a);
if (!a) abort();
for (i = 0; i < m; ++i)
a[i] = 0;

do {
for (i = m - 1; i >= 0; --i)
putchar(s[a[i]]);
putchar('\t');

for (i = 0; i < m; ++i)
if (++a[i] < n) break; else a[i] = 0;
} while (i < m);

putchar('\n');
free(a);

return 0;
}

Alex
Nov 14 '05 #3
On 26 Oct 2004 05:51:45 -0700
da************@ hotmail.com (darin dimitrov) wrote:
Hello,

I need help with an algoritm that given a set of "n" distinct
numbers will
generate all the possible permutations of fixed length "m" of these
numbers WITH repetitions (a total of n^m possibilities). For example:

given the set {1, 2} would output: 111,112,121,122 ,211,212,221,22 2 if
we fix m=3.

What I could do so far is an iterative algorithm which could be used
only if we know before runnin the program "m" and "n" which is not
often the case :)
You can run iterative algorithms where you only know the number of
iterations at run time.
int n=2; //stores the numebr of elements in the set
// comments are not recommended on Usenet since even if you use a
language where they are supported (which means C99 on this group) they
don't survive line wrapping. So you should stick to /* */ style
comments for posting.
int m=3; //stores the length of the desired permutation
char s[] = "12"; //stores our set of numbers
char s1[] = new char[m]; //will store every permutation generated (of
You seem to be talking a foreign language here. comp.lang.c++ is just
down the hall on the right. We only talk C here.
length 3)
See, the comment wrapped.
int i, j, k; // loop variables

for (i=0; i<length(s); i++) { // first loop
for (j=0; j<length(s); j++) { // second loop
for (k=0; k<length(s); k++) { // third loop
You could use a block of indexes and only one loop and increment the
indicies them like you do digits in a number when counting. I.e. when
one of them you keep going to you get to it's last valid value then next
time reset it an increment the next 1.
// this code is executed 2^3=8 times
s1[0] = s[i];
s1[1] = s[j];
s1[2] = s[k];
The above would then be a loop.
printf("%s\n", s1); // print the permutation
}
}
}
<snip>
Could you help me with some pseudo code please? And please appologize
me if the term "permutatio n" that I used here is not correct.


I've given you some hints. If you want to discuss algorithms further
then please take it to somewhere like comp.programmin g and if you want
to discuss problems with coding in C++ take it to comp.lang.c++. If, you
decide to implement it using C instead (using malloc/free instead of
new/delete, then once you have some code you can bring it here to
discuss it. I also suggest reading the FAQ (google for comp.lang.c FAQ).
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #4
Thanks to all of you who responded to my request despite the fact that
I posted some C/C++ mixture that wasn't very useful. The code I posted
was just to show my point (I never wrote in an editor). In fact I was
looking for the algorithm, more than its implementation and I should
have posted my question in comp.programmin g. But your posts were
excellent and helped me so much so I don't regret posting here. Flash,
I have taken into consideration your remarks.

Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
8293
by: Laphan | last post by:
Hi All This is a strange request, but I just cannot fathom how to do it. In theory the requirement is very basic, but in practise its a noodle!! I have 10 team names like so: Team A Team B
10
5686
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. Not being a computer scientist, I find recursive functions to be frightening and unnatural. I'd appreciate if anyone can tell me the pythonic idiom to accomplish this. Thanks for your help,
20
2304
by: John Trunek | last post by:
I have a set of X items, but want permutations of length Y (X > Y). I am aware of the permutation functions in <algorithm>, but I don't believe this will do what I want. Is there a way, either through the STL or some other library to do this, or do I need to write my own code?
6
4071
by: chiara | last post by:
Hi everybody! I am just at the beginning as a programmer, so maybe this is a stupid question...Anyway,I need to write a function in C to generate generate all possible strings of given length given a set of characters (allowing repetitions of the same character) For example given the characters 'E' and 'H' and maximum length 3 the function should generate the sequences
11
5928
by: Girish Sahani | last post by:
Hi guys, I want to generate all permutations of a string. I've managed to generate all cyclic permutations. Please help :) def permute(string): l= l.append(string) string1 = '' for i in range(0,len(string)-1,1): string1 = string + string
8
5053
by: girish | last post by:
Hi, I want to generate all non-empty substrings of a string of length >=2. Also, each substring is to be paired with 'string - substring' part and vice versa. Thus, gives me , , , , , ] etc. Similarly, 'abcd' should give me , , , , , ,, , , , , , ,] I've tried the following but i cant prevent duplicates and i'm missing
20
41317
by: anurag | last post by:
hey can anyone help me in writing a code in c (function) that prints all permutations of a string.please help
8
5639
by: Mir Nazim | last post by:
Hello, I need to write scripts in which I need to generate all posible unique combinations of an integer list. Lists are a minimum 12 elements in size with very large number of possible combination(12!) I hacked a few lines of code and tried a few things from Python CookBook (http://aspn.activestate.com/ASPN/Cookbook/), but they are hell slow.
9
1716
by: Alan Isaac | last post by:
I need access to 2*n random choices for two types subject to a constraint that in the end I have drawn n of each. I first tried:: def random_types(n,typelist=): types = typelist*n random.shuffle(types) for next_type in types: yield next_type
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10614
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10369
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10109
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.