Skip to content

feat: Sum of several arrays #92

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/code-challenges/code-challenges-003-010.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,37 @@ function simpleClockAngle(number) {
// gives us the number of degrees for one minute
return 6 * number;
}

/**
* Q004: Sum of several arrays
* Problem
* You will be given an array of several arrays that each contain integers and your goal is to write a function that will sum up all the numbers in all the arrays.
* For example, if the input is [[3, 2], [1], [4, 12]] then your program should output 22 because 3 + 2 + 1 + 4 + 12 = 22. Solve without and with reduce.
*/

// Normal
function multiDimensionalSumOfSeveralArrayVariationNormal(array) {
// Store our final answer
let sum = 0;
// Loop through entire array.
for (let i = 0; i < array.length; i++) {
// Loop through each inner array.
for (let j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
}

return sum;
}

multiDimensionalSumOfSeveralArrayVariationNormal([[3, 2], [1], [4, 12]]);
// reduce

function multiDimensionalSumOfSeveralArrayVariationReduce(array) {
return array.reduce((t, e) => t.concat(e)).reduce((t, e) => t + e);
}
multiDimensionalSumOfSeveralArrayVariationReduce([[3, 2], [1], [4, 12]]);

/**
* Q005: Test divisors of three
*/