dsasd12314
2018-09-05 13:00
浏览 40
已采纳

反向排名订单号,没有数组

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 ?

图片转代码服务由CSDN问答提供 功能建议

假设我们有一个排名系统,整数为1,最大为100.000。

我想要一个反转整数等级的函数。

因此,值100.000变为等级1,值1变为等级100.000。

  function reverseRank($ currentRank,$ maxRank){
 
 //创建数字1到$ maxRank的数组。
 //值的反向顺序和$ currentRank的返回键... 
 // 但这似乎有点浪费资源。
 
返回$ reversedRank; 
} 
   
 
 

这样做的最佳方法是什么? PHP?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyi1939 2018-09-05 13:14
    已采纳

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题