DeadBigHead - 3 months ago 32

C Question

`#include<stdio.h>`

int main()

{

int i, j, k;

for (i = 0; i <= 7; i++)

{

for (j = i+1; j <= 8; j++)

{

for (k = j+1; k <= 9; k++)

{

printf("%d%d%d\n", i, j, k);

}

}

}

}

I have this algorithm. It generates all 120 unique numbers. Maybe i am dumb, but i don't understand one simple thing.

If I remove +1 from both inner loops variable initialization, I will receive 720 unique combinations. With this +1 I am receiving 120, that does not repeat. So it clears out numbers so there are no numbers like 517 and 715, for example.

Can somebody explain how adding +1 to inner loops removes all different arrangements and only leaves one? Because there must be at least 6 unique sets of 120 numbers.

Answer

When you print the first set of digits, you have:

```
i j k --> i i+1 j+1 --> i i+1 i+2 --> 0 1 2,
```

and after the first completion of the `k`

-loop you have:

```
i j k --> 0 1 9.
```

Then the `j`

-loop is continued, with:

```
i j k --> 0 2 3.
```

If the initial values of the `j`

- and `k`

- loops were not incremented, then you would have:

```
i j k --> i i i --> 0 0 0
....
i j k --> 0 0 9
i j k --> 0 1 1,
```

and the sets would contain duplicate digits.

The algorithm gets all of the sets of three unique digits because it finds first all such sets that begin with `0 1`

, and then all such sets that begin with `0 2`

, ..., and then all such sets that begin with `1 2`

, ..., and finally all such sets that begin with `7 8`

, of which there is only one: `7 8 9`

.