number producing algorithm
Derek R. Foster
dfoster at jarthur.Claremont.EDU
Sat Apr 14 18:20:16 AEST 1990
In article <19416 at boulder.Colorado.EDU> baileyc at tramp.Colorado.EDU (BAILEY CHRISTOPHER R) writes:
>Help! I need an algorithm to generate a series of numbers. This series is
>of variable length. For example, if I pass a 10 to the function, it needs
>to generate numbers that have 10 digits. The catch is that the numbers it
>generates can not have more than one of the same digit, so say, the passed
>number is 3, it would generate the following:
>
>0 1 2
>0 2 1
>1 0 2
>1 2 0
>2 0 1
>2 1 0
>
>So, basically, there are n! number of combinations/permutations (whichever
>it is). Also, I would like it to start with 0 1 2 ...
This was a fun one to do. I like little challenges like this; they're
a like crossword puzzles. I found a reasonably nice solution to it.
It seems to work OK, although you might be able to eliminate the
recursion with a little massaging.
Try this:
#include <stdio.h>
void recurse(int *numlist, int num, int maxnum)
{
int i,j,norepeats;
if (num >= maxnum)
{
for (j=0; j<maxnum; j++)
printf("%d ", numlist[j]);
printf("\n");
fflush(stdout);
}
else
for (i=0; i<maxnum; i++)
{
for (j=0,norepeats=1; j<num && (norepeats=(numlist[j] != i)); j++);
if (norepeats)
{
numlist[num] = i;
recurse(numlist, num+1, maxnum);
}
}
}
void generatelist(int num)
{
int * numlist;
numlist = (int *) malloc(sizeof(int) * num);
recurse(numlist, 0, num);
free(numlist);
}
void main(void)
{
int num;
printf("Enter number?");
scanf("%d", &num);
generatelist(num);
}
I hope this is what you wanted!
Derek Riippa Foster
More information about the Comp.lang.c
mailing list