Greatest of three numbers using switch case

10,591

Solution 1

It's kinda stupid, but here you go.

switch(1)
{
    default:
        return Math.max(a, Math.max(b, c));
}

Solution 2

Not sure why you want to write the world's most complex snippet of code to find the max of three integers. This one is more readable, yet still complex enough to keep you amused...

public int main( int a, int b, int c)
{
    return Collections.max( Arrays.asList( new Integer[]{a,b,c} ));
}
Share:
10,591
YogeshAgar
Author by

YogeshAgar

Updated on July 10, 2022

Comments

  • YogeshAgar
    YogeshAgar almost 2 years

    I want to find out the greatest number, out of three given numbers, using switch-case(without using if) I answered the question using this program, which works:

    class GreatestNoSwitch{
        public int main(int a, int b, int c){
            int d = (int)Math.floor(a/b);
            int max = 0;
            switch(d){
                case 0:
                    max = b;
                    break;
                default:
                    max = a;
            }
    
            d = (int)Math.floor(max/c);
    
            switch(d){
                case 0:
                    max = c;
            }
            return max;
        }
    }
    

    Does anyone have any simpler answer?

    • Emil Vikström
      Emil Vikström almost 12 years
      What is your question? Is your code working?
    • marc wellman
      marc wellman almost 12 years
      StackOverflow is Question & Answering site. Post a question and we'll try to find an answer or at least help you finding an asnwer.
    • Marko Topolnik
      Marko Topolnik almost 12 years
      Without constraning what functions are allowed, this question doesn't make much sense.
  • Chris Gessler
    Chris Gessler almost 12 years
    @MarkoTopolnik - better?
  • Marko Topolnik
    Marko Topolnik almost 12 years
    Why would it be better? You are still using variables in case clauses.
  • Chris Gessler
    Chris Gessler almost 12 years
    @MarkoTopolnik - only constants... I see. This is a stupid puzzle anyway, and my answer is equally stupid. So they fit!
  • Marko Topolnik
    Marko Topolnik almost 12 years
    A perfect fit indeed! That's exactly what I meant when I said that without constraints on allowed functions, the puzzle is stupid.
  • YogeshAgar
    YogeshAgar almost 12 years
    I now feel hat this was a stupid puzzle... Thanks
  • Chris Gessler
    Chris Gessler almost 12 years
    @YogeshAgar - only in its current state, but could be the start of a great puzzle if you could figure out the limitations to make people think. I'm not sure that adding a rule like "without using a default case" would be solvable, but give it a shot.