O
O
Old Odessa2015-01-03 17:49:37
Programming
Old Odessa, 2015-01-03 17:49:37

How to find out of 4 numbers, where 3 are equal to each other, one is not equal, at a time?

Tell me how, using the minimum number of conditional operators, to find out of 4 numbers, one is not equal, if the remaining 3 are equal to each other.
Only without loops and arrays, only conditional statements.
I was told that this is related to the problem of three coins, supposedly the same algorithm.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
R
Roman Kitaev, 2015-01-03
@deliro

In 4 equal numbers, there is no one that is not equal.
0 comparison operators. I'm done?

M
Mrrl, 2015-01-03
@Mrl

It is necessary to clarify - what to count, comparison operations, or conditional operators. Count written operations/statements, or in progress.
Possible solutions:

int X[4];
return X[(X[0]==X[2])+2*(X[0]==X[1])];

int f(int p,int q,int r){
  return p==r ? q : p;
}
int g(int a,int b,int c,int d){
  return a==b ? f(c,d,a) : f(a,b,c);
}

int x=a^b,y=a^c;
x=(x|-x)>>31; y=(y|-y)>>31;
return ((a^b^c^d)&x&y)^((b^d)&x)^((c^d)&y)^d;

(the latter has no comparisons and conditional statements at all).

R
Rsa97, 2015-01-03
@Rsa97

Without explicit conditions, but with floating arithmetic, therefore it is inaccurate:
With one condition for positive numbers:

x = x1+x2-x3-x4;
if (0 > x) x = -x;

D
Dmitry Korolev, 2015-01-03
@Apathetic

I could only come up with two comparisons. For one thing I can’t imagine how =)
https://jsfiddle.net/mjdtfbkq/1/

A
Alexey Lebedev, 2015-01-03
@swanrnd

JavaScript:

a1=3; a2=2; a3=3; a4=3;
a1*!(2*a2-a3-a4)+a2*!(2*a3-a4-a1)+a3*!(2*a4-a1-a2)+a4*!(2*a1-a2-a3)

0 conditional.

U
uvelichitel, 2016-01-04
@uvelichitel

Compare any two, this comparison will give you a pair of known 'good' and a pair of fake in any outcome. The second comparison is to compare the obviously good with any of the pair with a fake. This will give the answer. Two comparisons.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question