I cannot retain the multiplied indices of the two arrays and add them, it always retains and multiplies the last indices.

For this example, I have values {1, 2, 3} and weights {0.1, 0.2, 0.7} and it should do something like this: 1*0.1 + 2*0.2 + 3*0.7 which will give me 2.6.

I have no problem doing this 1*0.1, 2*0.2 and 3*0.7, but it only retains the last indices and gives me 2.1 instead.

public static void main(String[] args) 
{
    double[] values = {1, 2, 3};
    double[] weights = {0.1, 0.2, 0.7};
    System.out.println(weightedSum(values, weights));
}

public static double weightedSum(double[] values, double[] weights)
{
    double multiply = 0;    
    double sum = 0; 
    for (int i = 0; i < values.length; i++){ 
        multiply = values[i]*weights[i];
    }
    return multiply;
}

3 Answers

2
Elliott Frisch On Best Solutions

You are returning multiply, and not doing anything with sum. Instead, perform addition on your multiplicands and then add them to sum. Like,

public static double weightedSum(double[] values, double[] weights) {
    double sum = 0;
    for (int i = 0; i < values.length; i++) {
        sum += values[i] * weights[i];
    }
    return sum;
}
1
Prabin Paudel On

The easiest solution as long as two arrays are of same length is following :

    //Multiply two arrays of size 3 and output sum
    int arr1[] = {1,2,3};
    double arr2[] = {0.1, 0.2, 0.7};
    final int LENGTH = 3;
    double result = 0;
    for(int i=0; i < LENGTH; i++) {
        result += arr1[i]*arr2[i];
    }
    NumberFormat formatter = new DecimalFormat("#0.00");     
    System.out.println("The result is " + formatter.format(result));
1
SRINIVAS MACHERLA On
// functional style - The easiest solution as long as two arrays are of same length is following:

public static double weightedSum(double[] values, double[] weights) {
    return IntStream.rangeClosed(1, values.length)
                    .mapToDouble( i -> values[i] * weights[i])
                    .sum();
}