I have three (int) variables, say code1, code2, code3. What is a good way to find if 2 or 3 from them are the same. I can do it but I am also sure that there is some neat trick to do it.
I am sending simple wireless commands to DUE via HC12 and sending the command 3 times helps keep out false readings.
That is the way if all three match but what if only 2 of them are same. And what is the value then. In my case it means that has been a single error in transmission, but it is not important.
I think about making two arrays, one with values and the other with counts how many times that value was found.
if (code1 == code2) matches++ ;
if (code1 == code3) matches++ ;
if (code2 == code3) matches++ ;
if (matches >= 2) { …
… but a GOOD checksum and a "serial number" in the commands may be a better solution.
Well. Yes, but I have do things about which I have some understanding.
int matches1 ....
if (code1 == code2) matches12++ ;
if (code1 == code3) matches13++ ;
if (code2 == code3) matches23++ ;
if (matches1 >= 2) { …
But now when I think more of this, there is better way. There are about 8 comparisons (with 3 variables). I could do nested ifs if I am carefull. With 4 or variables this gets too long.
explanation
1,1,1=1
1,1,2=1
2,3,3=3
2,4,2=2
2,3,5=-
Edit:Lets see what others say
Edit2: I don't mean to stop vaj4088 answering, but vaj4088 answered while I was writing.
LMI1: That is the way if all three match but what if only 2 of them are same.
No, it does exactly what you asked for. If all three are the same then any two are the same so you only need to check the three possible pairs to see if any pair matches. That what you asked for. That's what I wrote. If you WANTED to "find if all 3 from them are the same", that would have been:
if (code1 == code2 && code2 == code3)
LMI1:
And what is the value then.
You didn't ask that. You wanted "to find if 2 or 3 from them are the same." If you want to find the majority value, see reply #7 by MorganS.