Paolo_Mulder
Paolo_Mulder

Reputation: 1289

Reverse ranking order numbers , without an array

Let's say we have a ranking system with integers 1 till a maximum of 100.000 .

I want a function that reverses the rank of an integer.

So that value 100.000 becomes rank 1 and value 1 becomes rank 100.000 .

function reverseRank($currentRank,$maxRank){

         // create array with numbers 1 till $maxRank.
         // reverse order of values and return key of $currentRank...
         // but this seems a bit a waste of resources.

         return $reversedRank;
}

What would be the best way to do this performance wise in php ?

Upvotes: 2

Views: 280

Answers (1)

matiit
matiit

Reputation: 8017

Lets assume for simplicity that you have a range of ranks between 1 and 10.

We need to find a mapping function that will swap

1  -> 10
2  -> 9
3  -> 8
4  -> 7
5  -> 6
6  -> 5
7  -> 4
8  -> 3
9  -> 2
10 -> 1 

Now it might be easier to think about the solution.

What function will work for it? This function will have a couple of things known in the runtime. Lower and upper bands of the range, so 1 and 10 respectively.

We can sketch this in slightly more formal way:

f(1) -> 10
f(2) -> 9 
f(3) -> 8
(...)
f(x) -> y; // 1 and 10 are know to be the limits

what if we try to apply

Lets try playing with it. f(1) to be 10 could be:

def f(x):
    return x*UPPER_LIMIT

Definitely it will break as soon as we try it with 2.

F(2) -> 9, looking at this I am able to observe that I can write it as:

Lets return a number that is as much smaller from UPPER limit as the x is more than LOWER limit.

def f(x):
    return UPPER_LIMIT - (x-LOWER_LIMIT)

And, by running it for more values it looks like it works.

I hope I understood your question and that helps.

Upvotes: 3

Related Questions