Tuesday, 14 January 2014

Given two values from a serie of numbers find the shortest distance

package code {
   
    public class findShortestDistance{
       private var total:Number =32;
      
        public function findShortestDistance(from:Number, to:Number):Number {
            var CountergoLeft:Number = 1; var CountergoRight:Number = 1; var pivot:Number;
                pivot = from;
                while ((pivot = getPrevNum(pivot)) != to) {//Search backwards mean while "from" is different "to" 
                    CountergoLeft++;//Increase counter Left
                }
              pivot = from;
                while ((pivot = getNextNum(pivot)) != to)  {//Search forwards mean while "from" is different "to" 
                    CountergoRight++;//Increase counter Right
                }
                return (CountergoLeft < CountergoRight) ? CountergoLeft * -1 : CountergoRight;//if right times are bigger than left ones than go left with a negative value ( CountergoLeft * -1 ) otherwise go right  (pivot 25 , to 2 =>(23 CountergoLeft - 9 CountergoRight)  returns the shortest distance - 9- to right side)
        }
       
         private function getPrevNum(num):Number {
                if ((num - 1) == 0) {
                    return total;
                } else {
                    return num - 1;
                }
            }

         private function getNextNum(num):Number {
                if ((num + 1) > total) {
                    return 1;
                } else {
                    return num + 1;
                }
            }

    }
   
}