title: Dividing a space in a given number of cells depending on its size
body: <p>I recently started coding using P5.js and the browser editor they provide. You can find the code I'm talking about below at <a href="https://editor.p5js.org/Y_P/sketches/Xo2exzHSX" rel="nofollow noreferrer">https://editor.p5js.org/Y_P/sketches/Xo2exzHSX</a></p>
  
  <p>1- I'm looking for an algorithm to split a given screen space optimally into rows and columns so it follows the ratio. The inputs would be the width/height of the space, and the minimum number of cells you want. It would return the row and column that would be optimal to fit those cells.
  My first iteration seems to work but favor ratio offset too much. I'm curious about other options that might exist and be more efficient.</p>
  
  <p>2- I would also like to make a function to constrain the ratio in a certain range and can't wrap my head around it. </p>
  
  <p>Is anyone good enough in Math or any knows an HTML/JS function I could use? :)</p>
  
  <p>EDIT: I put the code right there because in case you don't want to follow the link above:</p>
  
  <pre><code>function setup() {
  
    spaceW = 1600;
    spaceH = 500;
    unit = 30;
  
    //constrainRatio(700, 200, 0.5, 1.5);
  
    createCanvas(spaceW, spaceH);
    background(51);
  
    let division = divideSpace(spaceW, spaceH, unit);
    for (let i = 0; i &lt; division.x; i++) {
      for (let j = 0; j &lt; division.y; j++) {
        rect(spaceW * i / division.x, spaceH * j / division.y, spaceW / division.x, spaceH / division.y);
      }
    }
  }
  
  function divideSpace(w, h, unit) {
    base = ceil(sqrt(unit));
  
    if (round(w / h) != 1) {
      if (h &lt; w) {
        ratio = h / w;
        column = ceil(ratio * base);
        row = ceil(unit / column);
      } else if (h &gt; w) {
        ratio = w / h;
        row = ceil(ratio * base);
        column = ceil(unit / row);
      }
    } else {
      row = base;
      column = base;
    }
    return createVector(row, column);
  }
  </code></pre>