AS3 -sort array values and take average of ones in the middle

前端 未结 1 1141
情深已故
情深已故 2021-01-25 23:01

Trying to create the AS3 equivalent of both median and averaging filters.

An averaging filter would simply be getting the average values of an array\'s contents.

1条回答
  •  后悔当初
    2021-01-25 23:36

    Assuming you have an Array (or Vector) of numbers:

    Use sort() with Array.NUMERIC:

    numbers.sort(Array.NUMERIC);
    

    Use slice() to copy a sub-set of the sorted array:

    var middleIndex:int = numbers.length / 2;
    var middleNumbers:Array = numbers.slice(middleIndex - 2, middleIndex + 2);
    

    Write a function which uses a for loop to iterate over the elements and sum them, then divide the sum by the array's length:

    function average(numbers:Array):Number {
        var sum:Number = 0;
        for each(var n:Number in numbers){
            sum += n;
        }
        return sum / numbers.length;
    }
    

    For the median, you want the middle number if the length is odd, or the average of the two middle numbers if the length is even:

    function median(numbers:Array):Number {
        var middle:Number = numbers.length / 2;
        if(middle is int){
            return numbers[middle];
        }else{
            return (numbers[int(middle)] + numbers[int(middle) + 1]) / 2;
        }
    }
    

    0 讨论(0)
提交回复
热议问题