Posted by Benjamin Johnston on 1999-05-01
>There's a couple things I want to say no. ! thanks for the reply no. 2
>although I can convert this to C you probably should have... it has 1
>minor error that I noticed while looking over the code.... it never
>switches any elements around... meaning it'll print the same thing over
>and over n! times...
It doesn't need to switch elements around, and it does work, I tested it in
Java before I posted it.
It displays the results on the screen, if you needed a rearranged array, it
would be easy to modify the code where the println() calls are made and
construct another temporary array there, on each pass.
What it does is each level of recursion "reserves" an element of "int[]
array", it then calls the next level of recursion.
When all the elements of "int[] array" are reserved, the "reservations" are
displayed on the screen.
Each layer of recursion reserves the first unreserved element and then calls
the next layer.
When the layer below returns, the first reservation is "freed" and the
second unreserved element is reserved.
This continues until there are no more elements to reserve, and the layer of
recursion returns.
Its a bit hard to explain it, maybe you should just try it out and play
around with it.
I converted it to C for you (the sorted version)...
(I haven't tested it with a c compiler, only a c++ compiler; but I don't
think I've used any thing that isn't in c -- and yes it does work correctly
in c++).
#include <stdio.h>
int array[] = { 1, 2, 3 };
int temp[] = { 0, 0, 0 };
int arraylength = 3; /* Make sure that this equals the length of array[] */
void combinations(int depth)
{
int i;
int j;
if (depth==arraylength)
{
for (i=0; i<arraylength; i++)
for (j=0; j<arraylength; j++)
if (temp[j]-1==i)
printf("%i", array[j]);
printf("\n");
}
else
{
i=0;
do
{
if (temp[i]==0)
{
temp[i]=depth+1;
combinations(depth+1);
temp[i]=0;
};
i++;
} while (i<arraylength);
};
return;
};
/* Following method declaration may be incorrect, in C it might only be "int
main(void)" -- I can't remember */
int main(int argc, char **argv)
{
combinations(0);
return 0;
}
---------------------------------------------------------------
THE CODE ENDS HERE
Actually, its almost a direct copy and paste... but if you don't know Java,
I guess it could be a bit confusing.
I hope it works for you.
(its probably not the pinnacle of optimized code, but it works)
-Benjamin Johnston
s355171@xxxxxxx.xx.xxx.xx
Previous post | Next post | Timeline | Home