0

My simple loop is coded

for (int i = 0; i < 3; ++i)
            {
                for (int j = 0; j < 3; ++j)
                {
                    Console.WriteLine("i = {0} j = {1}", i, j);
                }
            }

The output being

i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2

How can I change my loop so the combinations for i and j are always unique, even when swapped?

In other words

i = 0 j = 0 -- Unique
i = 0 j = 1 -- Unique
i = 0 j = 2 -- Unique
i = 1 j = 0 -- NOT Unique as 0 1 has occured before
i = 1 j = 1 -- Unique
i = 1 j = 2 -- Unique
i = 2 j = 0 -- NOT Unique as 0 2 has occured before
i = 2 j = 1 -- NOT Unique as 1 2 has occured before
i = 2 j = 2 -- Unique

Has anyone got any idea how this is possible to achieve?

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by DaveTran
2

Always let j be >= i so it doesn't cover old ground.

int maxIndex = 5;

    for (int i = 0; i <= maxIndex; i++)
    {
        for (int j = i; j <= maxIndex; j++)
        {
            Console.WriteLine("i = {0} j = {1}", i, j);
        }
    }

Edited by apegram: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.