I'm not sure the proper way to go about this recursively. Let's say I have two arrays
array1 = [a, null, c, d, e]
array2 = [1, 2, 3]
I want to create a resulting array of the form
[
[a, 1, c, d, e],
[a, 2, c, d, e],
[a, 3, c, d, e]
]
where each element of the second array fills in the place of null. I was able to do this just fine, but what if I have two cases of null?
array1 = [a, null, c, null, e]
array2 = [1, 2, 3]
how do I get the following?
[
[a, 1, c, 1, e],
[a, 1, c, 2, e],
[a, 1, c, 3, e],
[a, 2, c, 1, e],
...
[a, 3, c, 3, e]
]
CodePudding user response:
The first case you describe is an instance of map
pattern, and the second -- flatMap
.
Seen otherwise, map
is just like a loop, and flatMap
is like a two-level nested loops, creating the result's elements one by one from the deepest level loop:
Map:
for x in [1, 2, 3]:
let res = { result of replacing
the first `null` with `x`
in [a, null, c, d, e] }
yield res
-------------------------
[a, null, c, d, e]
----------------------
1 [a, 1, c, d, e],
2 [a, 2, c, d, e],
3 [a, 3, c, d, e]
flatMap:
for x in [1, 2, 3]:
let res = { result of replacing
the first `null` with `x`
in [a, null, c, null, e] }
for x in [1, 2, 3]:
let res2 = { result of replacing
the first `null` with `x`
in res } ## res NB!
yield res2
-------------------------
[ a, null, c, null, e ]
-------------------------
1: [ a, 1, c, null, e ],
1 [a, 1, c, 1 , e],
2 [a, 1, c, 2 , e],
3 [a, 1, c, 3 , e],
2: [ a, 2, c, null, e ],
1 [a, 2, c, 1 , e],
2 [a, 2, c, 2 , e],
3 [a, 2, c, 3 , e],
3: [ a, 3, c, null, e ]
1 [a, 3, c, 1 , e],
2 [a, 3, c, 2 , e],
3 [a, 3, c, 3 , e]
The first is like replacing each element in [1,2,3]
with the replacement result; and the second is like replacing each element in [1,2,3]
with the list of the replacement results and appending the resulting lists together; i.e. splicing the resulting lists' elements in place; i.e. creating the combined map, flattened (hence the name, flatMap
).
CodePudding user response:
Code on Javascript:
let array1 = ['a', null, 'c', null, 'e']
let array2 = [1, 2, 3]
let output = []
let count = 0;
let nullPositions = []
for (let i = 0; i < array1.length; i ) {
if (array1[i] === null) {
nullPositions.push(i)
}
}
const totalArray = Math.pow(array2.length, nullPositions.length);
for (let i = 0; i < totalArray; i ) {
output.push([...array1])
}
for (let i = 0; i < nullPositions.length; i ) {
count = 0;
let cutoff = totalArray / Math.pow(array2.length, i 1);
let increaseCutOff = cutoff;
for (let j = 0; j < output.length; j ) {
if (j < cutoff) {
output[j][nullPositions[i]] = array2[count];
} else {
cutoff = increaseCutOff;
count ;
if (count === array2.length) {
count = 0;
}
output[j][nullPositions[i]] = array2[count];
}
}
}
console.log(output);
Output:
[
["a",1,"c",1,"e"],
["a",1,"c",2,"e"],
["a",1,"c",3,"e"],
["a",2,"c",1,"e"],
["a",2,"c",2,"e"],
["a",2,"c",3,"e"],
["a",3,"c",1,"e"],
["a",3,"c",2,"e"],
["a",3,"c",3,"e"]
]