Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an array contains another array?

At first sight it's very simple, but I'm having some problems to do this without using a lot of nested loops.

Example:

var father:Array = new Array(0,1,2,3,4,5);
var son:Array = new Array(3,4,5);

father.contains(son) // returns true or 4(the starting index if the contained array)
like image 608
Marcelo Assis Avatar asked Nov 29 '25 04:11

Marcelo Assis


1 Answers

ActionScript 3 actually supports some slightly crazy stuff, due to the fact that, in the early days, Adobe/Macromedia were trying to make it compliant with Ecmascript.

So... you can do this:

var a1:Array = [1,2,3,4,5,6,7,8,9];
var a2:Array = [3,4,5];

// borrow String's indexOf function, and it magically works on Arrays
// but rename it because Array already has a different indexOf function
a1.indexOf2 = String.prototype.indexOf;

trace(a1.indexOf2(a2) > -1); // true

But you need to be a little bit careful because it will convert all the elements to Strings for the equality test. For primitives, it mostly won't matter but it will break badly with objects as they'll all be converted to "[object Object]" or to whatever their toString() returns.

Also, if you wanted to use the actual index for anything, rather than just checking it's not -1, you have to divide by two, as the number is double what you'd expect. I don't exactly know why this is :)

If you need something more general and reliable, you'd be better off writing a function to do an explicit search. This is a quick example, which I just wrote so could easily be bug-ridden:

    public function find(haystack:Array, needle:Array):int 
    {
        var index:int = -1;
        while(index <= haystack.length - needle.length)
        {
            index++;
            index = haystack.indexOf(needle[0], index);
            for( var i:int = 1; i<needle.length; i++)
            {
                if(haystack[index+i] != needle[i])
                {
                    continue;
                }
            }
            if( i == needle.length)
            {
                return index;
            }
        }
        return -1;
    }
like image 198
Peter Hall Avatar answered Nov 30 '25 17:11

Peter Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!