Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Alternate addition multiplication in an array - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns the alternative multiplicative sum of the elements.
For example, if the array is:
const arr = [1, 2, 4, 1, 2, 3, 4, 3];
Then the output should be calculated like this:
1*2 + 4*1 + 2*3 + 4*3 2 + 4 + 6 + 12
And the final output should be:
24
How It Works
The algorithm pairs consecutive elements starting from index 0. Each pair is multiplied together, then all products are summed. If the array has odd length, the last element is paired with 1.
Example
const arr = [1, 2, 4, 1, 2, 3, 4, 3];
const alternateOperation = arr => {
const productArr = arr.reduce((acc, val, ind) => {
if (ind % 2 === 1) {
return acc;
}
acc.push(val * (arr[ind + 1] || 1));
return acc;
}, []);
return productArr.reduce((acc, val) => acc + val);
};
console.log(alternateOperation(arr));
24
Step-by-Step Breakdown
const arr = [1, 2, 4, 1, 2, 3, 4, 3];
const alternateOperation = arr => {
console.log("Original array:", arr);
const productArr = arr.reduce((acc, val, ind) => {
if (ind % 2 === 1) {
return acc; // Skip odd indices
}
const product = val * (arr[ind + 1] || 1);
console.log(`Pair (${val}, ${arr[ind + 1] || 1}) = ${product}`);
acc.push(product);
return acc;
}, []);
console.log("Products array:", productArr);
const sum = productArr.reduce((acc, val) => acc + val);
console.log("Final sum:", sum);
return sum;
};
alternateOperation(arr);
Original array: [ 1, 2, 4, 1, 2, 3, 4, 3 ] Pair (1, 2) = 2 Pair (4, 1) = 4 Pair (2, 3) = 6 Pair (4, 3) = 12 Products array: [ 2, 4, 6, 12 ] Final sum: 24 24
Alternative Implementation
Here's a more direct approach using a simple loop:
const alternateOperationSimple = arr => {
let sum = 0;
for (let i = 0; i
24
Edge Cases
// Empty array
console.log("Empty array:", alternateOperation([]));
// Single element
console.log("Single element:", alternateOperation([5]));
// Odd length array
console.log("Odd length:", alternateOperation([2, 3, 4]));
Empty array: 0
Single element: 5
Odd length: 10
Conclusion
The alternate multiplication approach pairs consecutive elements, multiplies each pair, and sums the results. For odd-length arrays, the last unpaired element is multiplied by 1.
Advertisements
