I'm trying to fit an arbitrary number of HD videos on screen so that they all have equal size, maximizing the size of the videos, with no scrollbars appearing.

Given N number of tiles of equal aspect ratio (16:9), displayed in a viewport of arbitrary height and width, how can I resize the tiles so that:

a) all tiles are the same size
b) all tiles maintain their aspect ratio
c) all tiles fit within the viewport (i.e., no scrolling)
d) the tiles are as large as possible, while maintaining c)

  • 1
    What happens if you display isn't a 16:9 ratio? There will be left over screen area unused... Mar 23, 2016 at 1:24
  • @AdamZuckerman That's correct, unless the viewport aspect exactly matches the tiles, there will be extra space that can not be used. Assume the view port can be any size and aspect ratio. The algorithm must determine best fit.
    – RedFilter
    Mar 23, 2016 at 1:29

1 Answer 1


The purpose of this answer is to illustrate how one would approach a similar problem, regardless of language, and also to illustrate in a way that can be used for many different problems as well.


  • Scale factor s
  • Number of tiles horizontally nh
  • Number of tiles vertically nv


  • Viewport vw, vh
  • Original (full-size) video size w, h
  • Total number of videos n


  • Constraint 1: nh * w * s <= vw
  • Constraint 2: nv * h * s <= vh
  • Constraint 3: nh * nv >= n

Optimization goal

  • Maximize s


  • All values are strictly positive (none of them can be zero or negative.)


If you do not have a constraint solver, you can first enumerate the list of candidates of the pair (nh, nv), and then solve s for each candidate, and finally choose the one that maximizes s.

  • +1 I did not know there was a thing called a constraint solver :) That's fascinating. Off to explore that idea...
    – RedFilter
    Mar 24, 2016 at 0:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.