smatthewenglish
smatthewenglish

Reputation: 2889

calculate the average value across indicies of a hash map

I tried writing this code to test out my idea on how to calculate the average value across like indices of a hash map.
i.e. for each array contained within the hashmap if the first value for the first array was 2, and the first value for the second array was 4 , and the first value for the third array was 3, I want to assign the value of (4+3+2/3)= 3 to the final double[] array for the first index, and so on for all the indices 2 through n.

    int Size = 3;

    double[] AVERAGED_WEIGHTS = new double[Size];

    //store weights to be averaged. 
    Map<Integer,double[]> cached_weights = new HashMap<Integer,double[]>();

    double[] weights = new double[Size];

   int iteration = 0;
   do 
   {
       weights[iteration] = Math.floor(Math.random() * 10000) / 10000;

       iteration++;

       //store weights for averaging
       cached_weights.put( iteration , weights );  
    } 
    while (iteration < Size);

    //calc averages
    for (Entry<Integer, double[]> entry : cached_weights.entrySet()) 
    {
        int key = entry.getKey();
        double[] value = entry.getValue();
        AVERAGED_WEIGHTS[ key - 1 ] +=  value[ key - 1 ]; 

        if (key == iteration) 
        {
            AVERAGED_WEIGHTS[ key - 1 ] /= key;
        }
    }
    for(int i = 0; i < weights.length; i++)
    {
       weights[i] = AVERAGED_WEIGHTS[i];
    }

This mimics the structure of the original program wherein the weights are populated through a do while loop. This code is broken though and does not sucessfully perform the operation described above. I've been searching online and trying different ways to fix it but I've not been able to solve it. Perhaps someone can spot my faulty logic.

Upvotes: 0

Views: 1597

Answers (1)

DanielX2010
DanielX2010

Reputation: 1908

Maybe I misunderstood you, but you are not computing the average because for each array in your map, you are not taking into account all its positions. You are using the key and that makes absolutely no sense. Anyways, your code is very confusing. What you need to do is simply one loop inside the other. One going through the arrays and another going through the elements of each array. A way to compute the average is the following (in a didactic way):

//compute averages
double[] sums = new double[size];
double[] averages = new double[size];

for (Entry<Integer, double[]> entry : cachedWeights.entrySet()) {
    double[] value = entry.getValue();
    for(int pos=0; pos < Math.min(size, value.length); pos++){
        sums[pos] +=  value[pos]; 
    }
}
for(int pos=0; pos < size; pos++){
    averages[pos] = sums[pos] / cachedWeights.size(); 
}

Upvotes: 5

Related Questions