Search code examples
arraysactionscript-3flash

Convert list of pairs into array groups in AS3


I have an ActionScript 3 array that lists pairs of items like this:

pairs[0] = Array('ItemA', 'ItemB');
pairs[1] = Array('ItemA', 'ItemC');
pairs[2] = Array('ItemC', 'ItemD');
pairs[3] = Array('ItemC', 'ItemE');
pairs[4] = Array('ItemF', 'ItemG');
pairs[5] = Array('ItemF', 'ItemH');

And I need to loop over the array in some way to find all overlapping pairs (any pairs that share common pairs).

For example, ItemA is paired with ItemB and ItemC, so they belong in a group together. ItemC is also paired with ItemD and ItemE so they also need to be a part of the first group.

ItemF, ItemG and ItemH do not overlap with any of the items fromt he first group, so they need to be put into their own group.

The resulting array would need to be something like:

groups[0] = Array('ItemA', 'ItemB', 'ItemC', 'ItemD', 'ItemE');
groups[1] = Array('ItemF', 'ItemG', 'ItemH');

Thanks for any help and suggestions!

Edit:

A little bit of a back story; I'm trying to group together movie clips that overlap each other in 2D to create groups or clusters (might be a better word).

So if I have 3 movieclips on the stage and ClipA overlaps with ClipB and ClipB overlaps ClipC (but ClipA doesn't directly overlap ClipC) they should all be grouped together as they are all a part of the same cluster. This way should a new clip overlap any single item in a cluster, it will be added to that group's array.

I've already got the code worked out to find overlapping elements which is producing this pairs list, now I need to condense it into tidy groups.


Solution

  • After lots of playing around here's the solution I came up with.

    This will take an 2D overlapArray that has pairs and produce a group list with unique values.

    I used a in_array() function to duplicate PHP's handy function for finding if an item is already in an array.

    for each(var pair:Array in overlapArray) {
        var pairInGroup = false;
        for each(var group:Array in overlapArrayGroups) {
            if(in_array(pair[0],group) || in_array(pair[1],group)) {
                if(!in_array(pair[0],group)) {
                    group.push(pair[0]);
                }
                if(!in_array(pair[1],group)) {
                    group.push(pair[1]);
                }
                pairInGroup = true;
            }
        }
        if(!pairInGroup) {
            overlapArrayGroups.push(pair);
        }
    }
    

    The in_array() function:

    public static function in_array( needle:String, haystack:Array ):Boolean {
        for( var a = 0; a < haystack.length; a++ ) {
            if( haystack[a] == needle ) {
                return true;
            } else if( haystack[a] is Array ) {
                return in_array(needle, haystack[a]);
            }
        }
        return false;
    }