Search code examples
javascriptnumber-manipulation

get the number of the reverse order of a given series


I want to get the number of the reverse order of a given series in javascript. If I have the following series:

[1,2,2,2,5,5,7,8,8,10]

then if the input is number 8 the output should be 2, since:

 1  = 10
 2  = 7
 2  = 7
 2  = 7
 5  = 5
 5  = 5
 7  = 4
[8  = 2]
[8  = 2]
 10 = 1
//--> [1 , 2,3,4, 5,6, 7, 8,9, 10]
  --> [1 , 2,2,2, 5,5, 7, 8,8, 10]
      [10, 7,7,7, 5,5, 4, 2,2, 1 ] <-- // ==> [1,2,2,4,5,5,7,7,7,10]

Here is what I have done so far:

function getReverseNumber(arr, num)
{
    var newArr = new Array(arr.length);
    var temp;
    var counter = 1;
    for(var i = arr.length; i > 0; i--)
    {
        if(temp === arr[i])
        {
            newArr[arr.length - i] = counter;
            continue;
        }
        newArr[arr.length - i] = counter;
        temp = arr[i];
        counter++;
    }
    return newArr[num - 1];
}

but it doesn't work as expected:

getReverseNumber(new Array(1,2,2,2,5,5,7,8,8,10), 8) // returns 5 not 2

what is wrong in my function?


Solution

  • I think that you are overcomplicating it. You are only increasing counter by one when you increase it, and you place the numbers in revese order, so newArr end up as [1,2,2,3,4,4,5,5,5,6] instead of [10,7,7,7,5,5,4,2,2,1].

    There is no need to calculate all those numbers and keep in an array. Just loop from 1 and up, and calculate which position that is in the array. Return the index when you find the value:

    function getReverseNumber(arr, num) {
      for (var i = 1; i <= arr.length; i++) {
        if (arr[arr.length - i] == num) return i;
      }
      return -1; // not found
    }
    

    Demo: http://jsfiddle.net/Xedz6/