开发者

highest and smallest number in javascript using only switch statement

i am wondering how to use switch statement to tell which is the highest and lowest number in javascript, without using math.max in my script, any help开发者_C百科?


Pseudo-code only since it may be homework.

If it is, you should do some of the work yourself.

If it isn't you should be able to convert it to whatever language you want :-)

To work out the maximum and minimum of a and b:

def mymin(a,b):                   def mymax(a,b):
  switch (a-b):                     switch (a-b):
    case 0:                           case 0:
      return a                          return a
    default:                          default:
      switch ((a-b)/abs(a-b)):          switch ((a-b)/abs(a-b)):
        case -1:                          case -1:
          return a                          return b
        default:                          default:
          return b                          return a

It basically uses (a-b)/abs(a-b) which, assuming a and b are different will return -1 if b > a otherwise 1. You would get a divide-by-zero error if they were equal hence the outer switch to detect this first.

If you're looking for the minimum and maximum from a list, just set min and max initially to the first value in the list, then run through the list comparing each value with min and max and adjusting them accordingly:

def minAndMax(list):
    min = first element in list
    max = first element in list
    for each element e in list:
        min = mymin (min,e)
        max = mymax (max,e)
    return (min,max)


switch (true) {
   case a > b:
      min = b; max = a;
      break;
   case a < b:
      min = a; max = b;
      break;
   case a == b:
      // I know I could just use >= or <= 
      min = max = a;
}

Actually it's just uglier (or not?) form of if - else if - else statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜