Arrays with elements less or equal to the elements in given array


Arrays with elements less or equal to the elements in given array



What is the most JS-style way to solve the following problem?



Given an array A, find all arrays B, such that for i <= A.length: B[i] <= A[i]. Example of what I expect:


#Input
A = [1,2,0]
#Output
B = [[0,0,0],
[1,0,0],
[1,1,0],
[1,2,0],
[0,1,0],
[0,2,0]]



In Python I used:


B = [];
for t in [range(e+1) for e in A]:
B = [x+[y] for x in B for y in t]



Thanks in advance!




1 Answer
1



Use the following code (any loop for one item of the array a):


a


var a = [1, 2, 0], b = ;

for (var i = 0; i < a[0]; i++) {
for (var j = 0; j < a[1]; j++) {
for (var k = 0; k <= a[2]; k++) {
b.push([i, j, k]);
}
}
}



If you know the numebr of items in the array a only on runtime, use the following recursive function:


a


function fillArray(source, dest, recursionLevel, tempArr) {
if (recursionLevel >= source.length) {
dest.push(tempArr);
return;
}

for (var i = 0; i <= source[recursionLevel]; i++) {
var tempArr2 = tempArr.slice(); // Copy tempArr
tempArr2.push(i);
fillArray(source, dest, recursionLevel + 1, tempArr2);
}
}

fillArray(a, b, 0, );





Hey! Thank you for the answer. Although I don't quite understand the construction principle of the method. Why should we pass both A and B there, instead of having B being returned? What is the recursionLevel and why a user should input as a parameter? Why can't the forth argument be by default? Thanks!
– Krishal
Jul 1 at 18:30





@Krishal You shouldn't pass the arrays a and b as parameters, but doing this do the function reusable. The recursionLevel parameter indicate the number of times this function called itself (for example, 0 in the first iteration, 1 in the next, and so forth. Note, all iteration this function called recursively number of times (the for loop) with the same recursionLevel. But this recursionLevel will be greater in one than of the called function). Continue in the next comment
– חיים פרידמן
Jul 2 at 10:19



a


b


recursionLevel


for


recursionLevel


recursionLevel





Continue from the previous comment The empty array passed in the first call, is a temp array that the function uses. You can create a helper function, like function fillArrHelper(source, dest) { fillArray(source, dest, 0, ); }, and use it like fillArrHelper(a, b);.
– חיים פרידמן
Jul 2 at 10:19


function fillArrHelper(source, dest) { fillArray(source, dest, 0, ); },


fillArrHelper(a, b);






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Moria Casán

How to make file upload 'Required' in Contact Form 7?

Quinn's Post Commonwealth War Graves Commission Cemetery