best way to choose the majority among three [closed]
Edit: for what could be understood from explanations, answers and example:
I have three variables, each variable can assume just two specifics values. For example, this value can be 0 or 1.
I'd like a logic where the output would be the value which is present in the majority of the three variables.
For 开发者_JAVA百科example:
If
x=0
,y=0
andz=1
, the output would be 0.If
x=1
,y=0
andz=1
, the output would be 1.
There's an answer from @Femaref that gives a good result when the possible values are 0 and 1, but I need a generic solution, that can handle any possible values for the variables.
if((x+y+z) >= 2)
return 1;
return 0;
if x==y then return x else return z
This doesn't depend on the possible values being 0 and 1.
I'd use a table lookup. Convert your three bits of input into a number, and use that to index into an array holding the correct result for each possible input.
You could use simple math instead, and check for a sum >= 2, but it's hard to guess whether that's a good idea or not. It fits the requirement at hand, but it's not as open to easy modification, if that's ever likely to be needed.
Edit: The table-driven approach would look something like (syntax may be a bit off -- I've mostly done C++ lately):
int outputs[] = { 0, 0, 0, 1, 0, 1, 1, 1};
return outputs[a<<2 | b << 1 | c];
精彩评论