I have to list out all the sum of multiple array
For example I have a 2D array with dynamic length and the inititial length is 2, but the lenght will change dynamically.
Each element length must be 3.
function addSum(){
let length =3;
//calculate all sum of two array
let arrayGroup = [[1,2,3],[1,2,3]]
for(let i=0; i< length ;i ){
for(let j=0; j< length ;j ){
let sum = arrayGroup[0][i] arrayGroup[1][j]
console.log(sum)
}
}
}
//result in console should look like:
//2
//3
//4
//3
//4
//5
......and so on
Additional Info:
arrayGroup = [[1,2,3],[1,2,3]]
1 st sum= 1 1
2 nd sum= 1 2
3 rd sum= 1 3
4 th sum= 2 1
5 th sum= 2 2
6 th sum= 2 3
7 th sum= 3 1
8 th sum= 3 2
9 th sum= 3 3
This is all the sum of a 2-element array
if arrayGroup is 3 element array [[1,2,3],[1,2,3],[1,2,3]]
1 st sum= 1 1 1 // arrayGroup[0][0] arrayGroup[1][0] arrayGroup[2][0]
2 nd sum= 1 1 2
3 rd sum= 1 1 3
4 th sum= 1 2 1
5 th sum= 1 3 1
6 th sum= 2 1 1
7 th sum= 3 1 1
....and so on, until list all the combination
The above code is to show how I get result of two elements, however when the number element in arrayGroup become N, how can I get all result of N element (i.e arrayGroup = [[1,2,3],[1,2,3],.......,[1,2,3]])?
CodePudding user response:
what you are trying to compute is called cartesian product
of arrays, you can read this term ( or you will find cartesian product of sets
in mathematics )
function cartesian(arr1, arr2) {
const ans = [];
for(let x of arr1) {
for (let y of arr2) {
ans.push(x y);
}
}
console.log(arr1, arr2);
return ans;
}
let arr = [[1,2,3], [1,2,3], [1,2,3]];
let ans = [0];
for (let x of arr) ans = cartesian(ans,x);
console.log(ans)
also, we can simplify the code and make it shorter as well using some higher-order functions but try to understand the logic before going into syntactical improvements.
In short cartesian product is like multiplying two sets, what this code is doing is computing product for N lists by multiplying one list to the existing result at a time.
eg if you were to calculate a product of 1,6,5 you can do
ans = 1
for (let x in [1,6,5] ) ans = ans * x
Also note that if elements will always be [1,2,3], there can be faster methods to calculate the final result, because then there is a pattern to output as you are not calculating the cartesian product of random elements.
CodePudding user response:
This is solution if I understood your question properly.
function addSum(){
let length =3;
//calculate all sum of two array
let arrayGroup = [[1,2,3],[1,2,3]]
for(let i=0; i< length ;i ){
let secondArray = arrayGroup[1]
secondArray.forEach(a=>{
let result = arrayGroup[0][i] a
console.log(result)
})
}
}
addSum()