代码之家  ›  专栏  ›  技术社区  ›  Paolo_Mulder

逆序排列,不带数组

  •  2
  • Paolo_Mulder  · 技术社区  · 7 年前

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

    所以值100.000变为秩1,值1变为秩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;
    }
    

    1 回复  |  直到 7 年前
        1
  •  3
  •   matiit    7 年前

    为了简单起见,我们假设您有一个介于1和10之间的列组范围。

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

    现在考虑解决方案可能更容易了。

    什么功能对它起作用?这个函数在运行时会有一些已知的东西。

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

    如果我们试着申请呢

    def f(x):
        return x*UPPER_LIMIT
    

    我们一试这个肯定会坏的 2 .

    让我们返回一个比上限小得多的数字,因为x大于下限。

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

    推荐文章