Print_combn

bibop1611 Posted messages 5 Status Membre -  
fiddy Posted messages 441 Registration date   Status Contributeur Last intervention   -
Hello,

I would like to write a function that displays all the different combinations of n digits in ascending order.
* n will be such that: 0 < n < 10.
* If n = 2, it should give something like this:
01, 02, 03, ..., 09, 12, ..., 79, 89
* The prototype of the function must be:
void print_combn(int n);

So I was thinking of the following logic:

calculate the maximum value v of the number processed based on n (for example, for n = 3, v = 999)

loop from 0 to v

construct a string c of n characters from the current value (right justified, filled with 0 on the left if necessary)

traverse c and test that the characters are increasing

if so, display c

I started to write that as a piece of code but I can't continue...


void print_combn(int n)
{
int vmax = 10;
int i = 1;

while (i < n)
{
vmax *= 10;
i++;
}
i = 1;
while (i < vmax)
{
char tab[n];

i++;
}
}

Here, so help plz !!! :3

ps: the only function I am allowed to use is putchar.

Configuration: Linux / Firefox 24.0

2 réponses

fiddy Posted messages 441 Registration date   Status Contributeur Last intervention   1 847
 
Ah, too bad for putchar().
Otherwise, you could have made a for loop from 1 to v and only displayed the numbers that meet the condition (increasing digits).
Otherwise, in your program:
char tab[n];
I don't recommend that. It works in C99, but not for the reasons you think, and it might be considered incorrect by your teacher. You need to use dynamic allocation (malloc/calloc) and properly use free.

In terms of algorithms, you can do it more simply.
Let me point you in the right direction.
You need n for loops.
For the 1st, you loop from 0 to 9 (variable i) and display i
For the 2nd, you loop from i to 9 (variable j) and display j
For the 3rd, you loop from j to 0 (variable k) and display k
...

You just need to figure out the trick for the n for loops, for the variables i, j, k (hint: array).

Don't hesitate to post your program for corrections after considering this post.

Good luck.
--

Google is your friend.
0