AS3比较2个阵列

时间:2011-07-12 17:45:01

标签: arrays actionscript-3 compare

我很难解决这个问题。我有2个需要比较的未排序数组,array2必须包含array1的所有元素,array2可以包含任意数量的额外元素而不会影响结果。我没有看到排序数组和比较字符串值的任何好处,因为array2可能有额外的信息导致噪音。

var array1:Array;
var array2:Array;

// array2 must contain all elements of array1.

var array1:Array = new Array(1, 5, 6, 7);
var array2:Array = new Array(5, 9, 6, 4, 7, 8);
// comparing this should return false (array2 is missing and element from array1)

var array1:Array = new Array(1, 5, 6, 7);
var array2:Array = new Array(5, 9, 6, 4, 7, 1);
// comparing this should return true (array2 has all the elements of array1)

非常感谢任何正确方向的帮助。

5 个答案:

答案 0 :(得分:1)

这样的东西?

function checkContent($needles:Array,$haystack:Array):Boolean
{
    for each(var item:Object in $needles) {
        if($haystack.indexOf(item) == -1) return false;
    }
    return true;
}

答案 1 :(得分:1)

您可能还想考虑将对象(如果它们是对象)放在对象或字典中。这样就可以避免在对所有组件进行比较时出现可怕的缩放行为。

答案 2 :(得分:1)

最佳解决方案是对超集中的项进行散列,以便我们可以在恒定时间内查找它们。为此,我们可以使用Dictionary

然后,我们通过子集中的项目进行交互,以确定它们是否存在于超集中。请注意,我们记录了计数,这确保了我们也会尊重重复的项目。

该解决方案的最坏情况复杂性是O(M + N)。但是,由于我们突破了第二个循环,故障情况可以用最小的O(M + 1)完成。

function compare(subSet:Array, superSet:Array):Boolean {

    // Assume true unless proven otherwise
    var retVal:Boolean = true;

    var map:Dictionary = new Dictionary();

    // Place all items from superSet into the dictionary map for constant time
    // lookup, also maintain a count for each item to record duplicates.
    var item:*;
    for each(item in superSet) {
        if(!map[item])
            map[item] = 0;

        // Increment the count for this item in the dictionary
        map[item]++;
    }

    for each(item in subSet) {
        if(map[item])
            // Item exists, decrement count.
            map[item]--;
        else {
            retVal = false;
            break;
        }
    }

    return retVal;
}

答案 3 :(得分:0)

查看Array.every()Array.indexOf。但是,更好的方法可能是在ActionScript中阅读how Arrays work上的简单入门。

答案 4 :(得分:0)

FlexFiend指出了你正确的方向。字典对于这些问题非常有用,因为它们具有O(1)用于键查找/插入。

function contains(superSet:Array, subSet:Array):Boolean {
    var element:*,
        map:Dictionary = new Dictionary();
    for each (element in superSet) 
        map[element] = true;
    for each (element in subSet)
        if (map[element] != true) return false;
    return true;
}

这在O(M + N)中运行,这与未排序的数组一样好。