Search code examples
calgorithmcombinations

Generate all possible combinations of 3 digits without repetition


I'm trying to write a program that prints all possible combinations of three digits. And there is the constraint that:

  1. The three digits must be different
  2. 012, 120, 102, 021, 201, and 210 are considered the same combination of the three digits 0, 1 and 2
  3. Print only the smallest combination of three digits

The expected output is as follows

012, 013, 014, 015, 016, 017, 018, 019, 023, 024, 025, 026, 027, 028, 029, 034, 035, 036, 037, 038, 039, 045, 046, 047, 048, 049, 056, 057, 058, 059, 067, 068, 069, 078, 079, 089, 123, 124, 125, 126, 127, 128, 129, 134, 135, 136, 137, 138, 139, 145, 146, 147, 148, 149, 156, 157, 158, 159, 167, 168, 169, 178, 179, 189, 234, 235, 236, 237, 238, 239, 245, 246, 247, 248, 249, 256, 257, 258, 259, 267, 268, 269, 278, 279, 289, 345, 346, 347, 348, 349, 356, 357, 358, 359, 367, 368, 369, 378, 379, 389, 456, 457, 458, 459, 467, 468, 469, 478, 479, 489, 567, 568, 569, 578, 579, 589, 678, 679, 689, 789

I'm trying to implement in C but the algorithm or any language implementation will suffice.

Here is what I've done so far but it's inacurrate.

#include <stdio.h>

/**
 * main - entry point
 *
 * Description: display triple digits and ,
 *
 * Return: Always 0 (successful)
 */

int main(void)
{
    int i, j, k, l;

    i = 0;
    while (i < 1000)
    {
        j = i / 100; /* hundreds */
        k = (i / 10) % 10; /* tens */
        l = i % 100; /* units */
        if (j < k && k < l)
        {
            putchar(l + '0');
            putchar(k + '0');
            putchar(j + '0');
            if (i < 789)
            {
                putchar(',');
                putchar(' ');
            }
        }
        i++;
    }
    putchar('\n');

    return (0);
}

Solution

  • Here is a fairly compact snippet of code for giving the smallest unique three-digit number.

    #include <stdio.h>
    
    int main()
    {
        char digit[4];
    
        for (int i = 0; i < 8; i++)
        {
            for (int j = i + 1; j < 9; j++)
            {
                for (int k = j + 1; k < 10; k++)
                {
                    digit[0] = i + '0';
                    digit[1] = j + '0';
                    digit[2] = k + '0';
                    digit[3] = '\0';
                    printf("%s\n", digit);
                }
            }
        }
    
        return 0;
    }
    

    You can give that a try.