Radio
Radio

Reputation: 2853

Establishing an average when counts are portioned

The problem

I have an array which is a property of the class road, which defines the allowed vehicle types on the road, and supplies an approximate portion each type contributes to traffic:

[[bus,.2],[smallCar,.6],[bigCar,.2]]

I need to calculate the average length of the cars encountered on the road, given the proportion of traffic. (This is needed to do some basic calculations elsewhere in the class.)

What I have tried:

I can't quite wrap my head around a better way to do this. In my solution, fidelity changes with an increase in car count. This seems a really slow, heavy handed approach and not right. The function to improve is named averageVehicleLaneSpace.

A very paired down but working version of much larger classes:

road = function(){};
road.prototype.averageVehicleLaneSpace = function(){
    var sum = 0;
    var fakeCarCount = 10000;
    for( var i = 0; i< this.allowedVehicleTypes.length; i++){
        var type = this.allowedVehicleTypes[i][0];
        var perc = this.allowedVehicleTypes[i][1];
        for(n = 0; n<=fakeCarCount*perc; n++){
            sum += vehicle[type].laneSpace;
        }
    }
    return sum/fakeCarCount;
}


//define vehicles
var vehicle = {
    bus:{
        laneSpace:14
    },
    smallCar:{
        laneSpace:4
    },
    bigCar:{
        laneSpace:4.5
    }
};

var t = new road();
t.allowedVehicleTypes = [["bus",.1],["smallCar",.3],["bigCar",.6]];
alert(t.averageVehicleLaneSpace());

The Fiddle:

This Fiddle is the hopeful example above: The fiddle.

Upvotes: 0

Views: 27

Answers (1)

JuniorCompressor
JuniorCompressor

Reputation: 20025

The average is the sum of the ratio * laneSpace for each vehicle type. So calculating the average is as simple as:

road.prototype.averageVehicleLaneSpace = function(){
    var avg = 0;
    for (var i = 0; i < this.allowedVehicleTypes.length; i++) {
        var type = this.allowedVehicleTypes[i][0];
        var perc = this.allowedVehicleTypes[i][1];
        avg += perc * vehicle[type].laneSpace;
    }
    return avg;
}

Upvotes: 1

Related Questions