How to simplify checking if a pair of numbers is (1,2) or (2,1)?

Viewed 243

I need to make sure that a pair of numbers is either (1, 2) or (2, 1). Both x and y are always positive. The code I am using right now:

if ((x == 2 && y == 1) ||
    (x == 1 && y == 2)) {
    return 1;
}

It looks a little bulky, and I feel like it can be simplified. However, everything I tried resulted in false positives.

5 Answers

This is the most direct way to make this comparison.

It is also more readable than any alternative you may come up with, so no need to change it.

Here's one way to write it that I think is more readable:

if (std::set{x,y} == std::set{1,2})
{
    return 1;
}

Note that this is not as efficient as the version in your question. Don't write this in code that you're going to ship as a library, for example. But this is perfectly reasonable to write in your own programs when performance is not a concern.

Here's a demo.

The only way I could see you simplify it will be having a struct to represent you x and y, if this is some kind of coordinate, you could use something like vector2d or std::pair<int, int>

Then you could do :

    std::pair<int, int> valuePair = std::make_pair(x, y);
    if (valuePair == std::make_pair(1, 2) || valuePair == std::make_pair(2, 1))
    {
        return 1;
    }

Can the values be 0? Some say 0 is not positive or negative.

If X and Y are both > 0, then how about:

if( 3 == (x + y) ) { return 1; }

You might (ab)use std::minmax:

if (std::minmax(x, y) == std::pair<const int&, const int&>{1, 2})
{
    return 1;
}

or

if (std::minmax(x, y) == std::minmax(1, 2))
{
    return 1;
}

or (C++17)

if (auto [a, b] = std::minmax(x, y); a == 1 && b == 2)
{
    return 1;
}
Related