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

条形图轴的正确通用计算[重复]

  •  0
  • Mani  · 技术社区  · 7 年前

    有没有一种通用可靠的方法来计算条形图轴? 我在寻找一种算法,应该四舍五入到下一个“适当”的数字。

    In the image the y-axis is 0 - 300 with a sequence step of 75

    我认为这个算法应该接受一个数字数组,并且:

    a) 确定最小/最大值(在这种情况下为25和250)

    b) 确定“适当”最大值(在本例中为300)

    我在寻找一种智能的方法来取整任意数字。

    1 回复  |  直到 7 年前
        1
  •  1
  •   displayName    7 年前

    我已经在这里添加了225的输出将是该算法的230,而不是OP要求的300。理由:我的实现就是这样。这个问题真的没有正确的答案。这不仅仅是一个设计问题。


    想法:使用int到int的映射,如果key是数字,那么value是应该添加到其中以获得适当数字的值。从右端提取输入的数字,并继续改进从右端向左移动的数字,每次一个数字。


    添加剂 键,值 }配对如下:

    请注意,您不需要将每个整数都添加到其中。如果正确使用映射,只添加一些整数就足够了。

    以下是代码/伪代码,您可以从输入数字中获得适当的值:

    int GetProperNumber(int input) {
        //Init a variable to keep track of the sign
        int multiplier = 1;
    
        //For negative numbers, taking some precaution...
        if (input < 0) {
            input *= -1;
            multiplier *= -1;
        }
    
        //For cases where the input number is only 1 or 2 digits, some quick checks...
        int numberOfDigits = GetNumberOfDigitsInInput(input);
        if (numberOfDigits == 1) return (input + additive[input]) * multiplier;
        if (numberOfDigits == 2) return (input + additive[input - input/10]) * multiplier;
    
        //Now, coming to the core of the method
        int divisor = 10; //We'll use it to get the left part from the input
        while (true) {
    
            //First, get right part of the number
            int inputWithDigitsRemoved = input / divisor;
    
            //If the leftover part is too small, i.e. we have reached the last digit,
            //then break as we have now rounded the number off pretty well.
            if (inputWithDigitsRemoved <= 9) break;
    
            int inputWithDigitsMasked = inputWithDigitsRemoved * divisor;
            int right = input - inputWithDigitsMasked;
    
            //Since the number is still not rounded to the right magnitude, 
            //the result should be further improved.
            if (additive.Contains(right)) input += additive[right];
            divisor *= 10;
        }
        return input * multiplier;
    }
    

    一些样本结果是:

    输入=99,输出=100

    输入=2541,输出=2600