Determines whether a group of rectangles compose a complete rectangle.

Source: Internet
Author: User

Determines whether a group of rectangles compose a complete rectangle.

function rect(l, t, w, h) {    this.l = l; // left    this.t = t; // top    this.w = w; // width    this.h = h; // height}function check(rects) {    var data = [];    var i, t, b;    for(i = 0; i < rects.length; i++ ) {        t = rects[i].t;        b = t + rects[i] + h;        while (t < b) {            if (!data[t]) {                data[t] = {                    l: rects[i].l,                    w: rects[i].w                }            } else {                data[t].l = Math.min(data[t].l, rects[i].l);                data[t].w += rects[i].w;            }            t++;        }    }    for (i = 1; i < data.length; i++) {        if (!data[i] || (data[i].l != data[i - 1].l) || (data[i].w != data[i - 1].w)) return false;    }    return true;}

The time complexity of this method is O (h1 + h2 +... + Hn), which can be generally understood as O (n * avg (h). If there are many rectangles, but each height is relatively small, it is similar to O (n ), however, if there are few Rectangles and the height is very high, the efficiency is worse than O (n ^ 2.

There is another method below

function check(rects) {    var i, l = 10000, r = 0, t = 10000, b = 0, sum = 0;    for (i = 0; i < rects.length; i++) {        sum += rects[i].w * rects[i].h;        l = Math.min(l, rects[i].l);        r = Math.max(r, rects[i].l + rects[i].w);        t = Math.min(t, rects[i].t);        b = Math.max(b, rects[i].t + rects[i].h);    }    return ((r - l) * (b - t) != sum);}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.