【问题标题】:How to maximize grid dimensions given the number of elements如何在给定元素数量的情况下最大化网格尺寸
【发布时间】:2013-06-03 23:36:20
【问题描述】:

我有n 元素作为输入和一个函数make_grid(n),它将计算包含这些元素的网格的尺寸。假设n = 12,那么函数必须计算出宽度为4,高度为3,而不是1和12左右。同样,n = 24 应该返回 6 和 4。

我尝试使用ceil(sqrt(n)) 来获得一维,但根本不是一般情况,并且使用情况(偶数,sqrt(n) == ceil(sqrt(n)))没有奏效。

编辑: Finding the optimum column and row size for a table with n elements and a given range for its proportion 我已经看到了这个问题,但编码让我想到了 n = 24 维 5 和 5。 有什么帮助吗?

【问题讨论】:

    标签: python maximize


    【解决方案1】:

    您正在寻找将n 整除的数字,因此您需要计算n 的因数,并取最接近sqrt(n) 的两个数。一个是小于或等于sqrt(n) 的最大因子(称为f),另一个是n/f

    但是,对于许多数字,例如 74 或任何素数,您会得到看起来很奇怪的网格。

    【讨论】:

    • 确实,你是对的。数字之间的因素相距甚远的情况下,表格将太长或太高。我将使用保持某种屏幕比例的数字,所以这不是问题。不过我会考虑因素和srqt(n) 的想法。
    • 假设 n = 50,并且 floor(qrt(50)) = 7,但 7 不是因子 D:
    • 你是对的。它不是。不过,这不是我的建议。 50 的因数是 1、2、5、10、25 和 50。因此,最接近 sqrt(50) 的两个因数是 5 和 10,即为 5 x 10 或 10 x 5 的网格。
    • 好的,我明白你的意思了,在问任何问题之前,我必须仔细阅读答案。感谢您的耐心等待,我知道您的解决方案了。
    • 我不知道英语说得好不好,但我真正看的不是n的“因素”,我在看n的除数跨度>
    【解决方案2】:

    您正在寻找整数分解算法。

    在这里查看:Efficiently finding all divisors of a number

    在这里:http://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms

    然后只需选择最符合您目标的一对因素。

    【讨论】:

      【解决方案3】:

      方法如下:

      将整数n作为函数的输入。目标是获得“最平方”的表。正如@John 建议的那样,我们必须计算sqrt(n) 才能了解尺寸。另一方面,我们必须计算n 的所有除数,以便选择最接近sqrt(n) 的除数。

      我们如何选择最接近的低值?我们可以使用这个技巧(Python):finding index of an item closest to the value in a list that's not entirely sorted 并获取除数列表中最接近的值的索引,比如hIndex。 然后可以计算出另一个维度,将n 除以divisors[hIndex] 或使用新索引wIndex = hIndex + 1 得到divisors[wIndex]

      Python 代码是这样的(注意我使用了惰性求值来查找除数):

      import numbers
      from math import sqrt
      
      def get_dimensions(n):
          tempSqrt = sqrt(n)
          divisors = []
          currentDiv = 1
          for currentDiv in range(n):
              if n % float(currentDiv + 1) == 0:
               divisors.append(currentDiv+1)
          #print divisors this is to ensure that we're choosing well
          hIndex = min(range(len(divisors)), key=lambda i: abs(divisors[i]-sqrt(n)))
          wIndex = hIndex + 1
      
         return divisors[hIndex], divisors[wIndex]
      

      【讨论】:

        猜你喜欢
        • 2013-12-23
        • 1970-01-01
        • 2011-08-30
        • 2016-08-08
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 2012-05-22
        • 1970-01-01
        相关资源
        最近更新 更多