'How do you do pairwise muliplication?

So I am really new at coding (JAVA) and I need to do a pairwise multiplication. as an example, consider the list [ 2, 5, 6] the list returned should be [10, 12, 30]

So how do I make sure that they only multiplicate with the other numbers and not with themselves?



Solution 1:[1]

If I'm reading your question correctly, then it seems that you want to use a for-loop, and you're trying to get the product of all elements in an array except the current element.

If this is the case, then you example should be:

[2, 5, 6] => [30, 12, 10]

Here's my solution:

public int[] pairWise(int[] numbers) {
    int[] res = new int[numbers.length];
    for (int i = 0; i < numbers.length; i++) {
        int[] temp = new int[numbers.length - 1];
        System.arraycopy(numbers, 0, temp, 0, i);
        System.arraycopy(numbers, i + 1, temp, i, numbers.length - i - 1);
        int product = 1;
        for (int j = 0; j < temp.length; j++) {
            product *= temp[j];
        }
        res[i] = product;
    }
    return res;
}

This solution is pretty ineffective, since it uses 2 for-loops, which makes it O(n2).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NerdyGamer