Wednesday, July 15, 2015

merge regions

region has a color (black or white) or has 4 regions.
//examples

x denotes black, . denotes white

.x + .. = .x
..   x.   x.

xx.x + .... = xx.x
xx..   ....   xx..
....   ..xx   ..xx
....   ..xx   ..xx

i.e.:

? + x = x
? + . = ?
In-place is faster than creating a copy of region (especially regiongroup).
// objects
iregion:
    // nothing
region: iregion
    color //black or white
regiongroup: iregion
    iregions[] //always 4

// in-place
merge(r1, r2):
    if r1 == null || r2 == null:
        throw "invalid args"
    if r1 is region:
        return ((region)r1, r2)
    if r2 is region:
        return ((region)r2, r1)
    if r1 is regiongroup && r2 is regiongroup:
        rg1 = (regiongroup)r1
        rg2 = (regiongroup)r2
        if rg1.regions == null || rg2.regions == null
            || rg1.regions.count() != 4 || rg2.regions.count() != 4:
            throw "invalid args"
        rg = rg1
        for i = 0, i < 4, i++:
            rg.regions[i] = merge(rg1.regions[i], rg2.regions[i])
        return rg
    throw "out of range"

(region r, iregion rother):
    if r.color == color.black:
        return r
    if r.color == color.white:
        return rother
    throw "color out of range"

[Hat tip to V]

No comments:

Post a Comment