Home > Blockchain >  Listing permutations of two dice with one loop
Listing permutations of two dice with one loop

Time:10-29

As part of a coding challenge for myself, I've been trying to write code for simple problems in one line. Currently, I'm trying to print out all permutations possible for two dice. So far, I have a simple algorithm utilizing two for loops:

for(int i = 1; i <= 6; i  )
    for(int j = i; j <= 6; j  )
        printf("%d %d", i, j);

Which can be easily turned into one line:

for(int i = 1; i <= 6; i  ) for(int j = i; j <= 6; j  ) printf("%d %d", i, j);

Both programs output the permutations in the desired order:

1 1
1 2
1 3
1 4
1 5
1 6
2 2
2 3
2 4
2 5
2 6
3 3
3 4
3 5
3 6
4 4
4 5
4 6
5 5
5 6
6 6

In order to make this challenge harder, I'm trying to print out the permutations in the same order as the output above, using only one loop. I'm sure I'll need to use division and modulo in order to accomplish this, but I'm stuck and unsure how to achieve this.

CodePudding user response:

The 2 loop version is the most readable. But since you asked, here are some 1 loop versions:

int main()
{
    int n = 6;
    for (int i = 1, j = 1; i < n;   j) 
    {
        if (j > n)
        {
              i;
            j = i;
        }
        std::cout << i << " " << j << '\n';
    }

    std::cout << std::flush;
}
int main()
{
    int n = 6;
    int i = 1;
    int j = 1;
    while (true)
    {
        if (j > n)
        {
              i;
            j = i;
        }
        if (i > n)
        {
            break;
        }
        std::cout << i << " " << j << '\n';
          j;
    }
    std::cout << std::flush;
}

As a side note:

for(int i = 1; i <= 6; i  ) for(int j = i; j <= 6; j  ) printf("%d %d", i, j);

This is horrible. Don't ever write code like this. The artificial goal of writing code in one line is completely and utterly pointless. You can take any code and put it on one line like that without any effort so it has absolutely not benefit, teaching or otherwise.

There is the concept of writing one-liners but that is not just replacing new lines in source code with spaces. It's about e.g. replacing loops with function calls or chain calls.

And don't forget, first and foremost write correct, clean and readable code.

  • Related