-1

I have 4 numbers (int a, int b, int c, int d) that are equal to rand()%7. How can I discover if the numbers are equal to each other in the shortest way?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Bar Cohen
  • 51
  • 2
  • 5
  • 1
    Welcome to SO, please be a bit more specific when asking question: what have you tried, what do you expect, etc. See [how to ask](http://stackoverflow.com/help/how-to-ask) – Nehal Dec 28 '15 at 12:31
  • 7
    If (a==b && b==c && c==d) – Idos Dec 28 '15 at 12:31
  • Please don't use either `rand()` or (what perhaps is even worse) division by modulo (see e.g. http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator). As for your question, @Joachim is right. In such a small array the fastest way is to just compare each number with the following one. – ghostmansd Dec 28 '15 at 12:32

2 Answers2

4

To find out if the numbers are equal to each other, you can do:

if (a == b && b == c && c == d)

The condition above is supported by the transitive property of equality in mathematics in which it states that:

If a = b and b = c, then a = c.

Given that property, we can state:

If a = b, b = c, and c = d, then a = c, a = d, and b = d.

Source: Mathwords

Sean Francis N. Ballais
  • 2,338
  • 2
  • 24
  • 42
1

You can do this with a single test:

int x = (1 << a) | (1 << b) | (1<< c) | (1<< d);
if ((x & (x >> 1)) == 0)
     printf("a, b, c and d are identical\n");

It works because all values are small, less than the number of bits in an int. The test checks if x is a power of 2, which will only be true if all values of a, b, c and d are the same.

chux suggested a shorter solution:

if ((1 << a) == ((1 << b) | (1 << c) | (1 << d)))
    printf("identical\n");

It might not be shorter than the simple (a == b && b == c && c == d) in the number of instructions nor the computing time, depending on the specifics of your platform, compiler, options...

Here is a even simpler one that uses only one test and works for a larger range of values, for instance all positive int values:

if (((a - b) | (b - c) | (c - d)) == 0)
    printf("identical\n");
chqrlie
  • 131,814
  • 10
  • 121
  • 189