Max square size for unknown number inside rectangle

前端 未结 10 516
陌清茗
陌清茗 2020-12-03 07:58

If I have a set of tiles (squares) which can be any number and they are to fill a container (rectangle) of an unknown size how do I work out the maximum size of the tiles wi

相关标签:
10条回答
  • 2020-12-03 08:46

    Divide the longer side by the number of tiles. Use the shorter side as the tile size. Presto! # of tiles.

    Rectagle = 200 x 10
    Each tile is 10 x 10 (length of shorter side)
    200/10 = 20 (number of tiles needed)
    
    0 讨论(0)
  • 2020-12-03 08:50

    Given values:

    N - number of tiles
    a, b - sides of the rectangle
    

    side of a tile may be calculated using this function:

    def maxSize(n: Int, a: Int, b: Int) = {
      var l = 0
      for (i <- 1 until a.min(b)) { // 
        val newL = (a.min(b) / i).min( (a.max(b) * i)/n )
        if (l < newL && ((a.min(b)/newL) * (a.max(b)/newL) >= n )  )
          l = newL
      }
      return l
    }
    

    i have supposed that you are not going to make tiles smaller than 1x1, whatever the measure of 1 is

    first you start from the size 0:

    l = 0
    

    then you iterate from 1 to K columns of tiles where

    K = min(a, b)
    

    for every iteration calculate new maximum side of a tile using this formula

    val newL = ( a.min(b) / i ).min( (a.max(b) * i)/n )
    

    this formula takes the smaller on of these two values:

    1. min(a, b)/i -- maximum length of a tile if there are i columns in the smaller side of the rectangle
    2. (i * max(a, b))/n -- maximum length of a tile if there are i columns and n tiles in the bigger side of the rectangle
    

    if the candidate newL is greater than the initial value l and maximum possible number of tiles which can be put in the square without overlaping is greater or equal than number of tiles n then

    l = newL
    

    on the end return l

    0 讨论(0)
  • 2020-12-03 08:51

    Conceptually:

    • start with 1 square
    • For each additional square, if you don't have room in your grid box so far, shrink the existing box just enough to make room for an additional row or column.

    pseudocode: given M x N rectangle to fill with K squares

    // initial candidate grid within the rectangle
    h=1
    w=1
    maxsquares=1
    size=min(M,N) //size of the squares
    while K > maxsquares
      if M/(h+1) >= N/(w+1)
        h=h+1
      else
        w=w+1
      endif
      maxsquares=h*w
      size=min(M/h,N/w)
    done
    print size
    

    There are probably faster ways to jump to the answer for very large K, but I can't think of them. If you know that M and N are integers, there may be even faster methods.

    0 讨论(0)
  • 2020-12-03 08:56

    This is a packing problem. Optimal solutions are hard to find. See for example Packing N squares in a square.

    You can compute an (optimistic) upper bound by dividing the total surface by the number of squares: sqrt(width*height/n).

    0 讨论(0)
提交回复
热议问题