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.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化