E
E
Egor Knyazhev2016-04-15 22:58:40
Programming
Egor Knyazhev, 2016-04-15 22:58:40

How to iterate over paired combinations of objects in a linked list?

I can't figure out how to iterate over combinations of objects in a linked list from n to 2.
First, I started writing an algorithm on an array to make it easier. The result is a recursive function:

void combine(int index)
{
  for (int i = index + 1; i < LENGTH; i++)
  {
    cout << arr[index] << " " << arr[i] << endl;
    combine(i);
  }
}

But in this way the combinations are repeated.
What is the right way to enumerate all combinations of n by 2 and so that it is not too time-consuming?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MagnetonBora, 2016-04-15
@L0nger

Something like this.

void pairs()
{
    int arr[LENGTH] = {1, 2, 3, 4, 5};
    for (int i = 0; i < LENGTH; i++)
    {
        for(int j = i + 1; j < LENGTH; j++)
        {
            cout << arr[i] << " " << arr[j] << endl;
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question