Skip to content

Instantly share code, notes, and snippets.

@GuiRitter
Last active August 5, 2018 22:21
Show Gist options
  • Select an option

  • Save GuiRitter/aee01e7790e75c4b29460c9efeaac52d to your computer and use it in GitHub Desktop.

Select an option

Save GuiRitter/aee01e7790e75c4b29460c9efeaac52d to your computer and use it in GitHub Desktop.

Revisions

  1. GuiRitter revised this gist Aug 5, 2018. No changes.
  2. GuiRitter created this gist Aug 5, 2018.
    80 changes: 80 additions & 0 deletions FitRectangleInRectangle.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    public final class FitRectangleInRectangle {

    public static class Input {

    public int height;

    public int width;

    public Input() {}

    public Input(int width, int height) {
    this.width = width;
    this.height = height;
    }
    }

    public static class Output extends Input {

    public double scale;

    @Override
    public String toString() {
    return String.format("{width: %s, height: %s, scale: %s}",
    width, height, scale);
    }

    public Output() {}

    public Output(int width, int height, double scale) {
    super(width, height);
    this.scale = scale;
    }
    }

    public static final Output fitRectangleInRectangle(Input inner, Input outer) {
    Output output = new Output();
    if ((inner == null) || (outer == null)) {
    return null;
    }
    double innerAspectRatio = ((double) inner.width) / ((double) inner.height);
    double outerAspectRatio = ((double) outer.width) / ((double) outer.height);
    if (innerAspectRatio < outerAspectRatio) {
    output.scale = ((double) outer.height) / ((double) inner.height);
    } else {
    output.scale = ((double) outer.width) / ((double) inner.width);
    }
    output.width = (int) Math.round(output.scale * ((double) inner.width ));
    output.height = (int) Math.round(output.scale * ((double) inner.height));
    return output;
    }

    public static void main(String[] args) {
    System.out.println(fitRectangleInRectangle(new Input(500, 250), new Input(200, 50)));
    System.out.println(fitRectangleInRectangle(new Input(250, 200), new Input(200, 50)));
    }
    }

    /*
    TODO permute possibilites to make test cases
    ratio inner ? outer
    <
    =
    >
    size inner ? outer (completely contain or be contained to make it easier at first)
    <
    =
    >
    inner aspect ratio
    horizontal
    square
    vertical
    outer aspect ratio
    horizontal
    square
    vertical
    */