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 ?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能