The following code will generate 10 arrays, each with 10 subarrays, each with 10 subarrays, each with 10 subarrays.
paths = [];
for (var i = 0, len_i = 10; i < len_i; ++i) { // 1st dimension
paths.push([]);
for (var j = 0, len_j = 10; j < len_j; ++j) { // 2nd dimension
paths[i].push([]);
for (var k = 0, len_k = 10; k < len_k; ++k) { // 3rd dimension
paths[i][j].push([]);
for (var l = 0, len_l = 10; l < len_l; ++l) { // 4th dimension
paths[i][j][k].push([]);
paths[i][j][k][l] = [];
}
}
}
}
I will eventually need to do this with more dimensions and am curious to know if any ingenious developers out there can accomplish this with a function of the form:
function makePaths(quantityInEachArray, dimensions) {
paths = [];
quantityInEachArray = (typeof quantityInEachArray === "undefined") ? 10 : quantityInEachArray;
dimensions = (typeof dimensions === "undefined") ? 4 : dimensions;
// Do some magic
return paths;
}
That function, in its default form, would return the same thing as the for loops I demonstrated above.
I understand that this is not a standard practice but I am doing it for a very specific reason and need to test the performance of it.
How do I modify this code to produce nth dimensional arrays?
You can use recursive function:
function nthArray(n, l) {
if(n < 1) return;
var arr = new Array(l);
for(var i=0; i<l; ++i)
arr[i] = nthArray(n-1, l);
return arr;
}
A simple magic would be (without recursion):
paths = []
arrays = [paths]
for (var i = 0; i < dimensions; i++) {
tmpArr = []
for (var k = 0; k < arrays.length; k++) {
for (var j = 0; j < size; j++) {
val = []
tmpArr.push(val)
arrays[k].push(val)
}
}
arrays = tmpArr
}
(I am not very fluent in javascript, you probably need to declare vars at the beginning and every thing, but that's the idea)
Related
When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Error. I don't know why. My code here.
// r and c are already defined numbers,arr is already defined array.
let n = [[]]
let index = 0
for (let i = 0; i < r; i++) {
for (let j = 0; j < c; j++) {
n[i][j] = arr[index]
index++;
}
}
return n;
Leetcode told me n[i][j] = arr[index] had error;
Anyone knows why? thanks.
Whenever the value of i becomes 1, inside the inner loop it is setting the value to n[i][j], which is n[1][0], here n[1] is undefined and it is accessing the 0th index value of undefined, that is the reason of the error.
the first iteration works fine because there is already an empty array in the 0th index (when i = 0).
here you can try doing this
let n = []
let index = 0
for (let i = 0; i < r; i++) {
n[i] = [];
for (let j = 0; j < c; j++) {
n[i][j] = arr[index];
index++;
}
}
return n;
As the comments showed, it is possible to use .push.
This is how I implemented that solution in my case.
const myArray = [[]];
const height = 7;
const width = 8;
for (let i= 0; i < height; i++) {
if (i> 0) myArray.push([]); // this initialises the array.
for (let j = 0; j < width; j++) {
myArray[i][j] = "x";
}
}
console.log(myArray)
Here is a codepen
Is it possible to .push() a value to an array but replicate the pushed value n times without using a traditional loop to perform the replication? For instance using .fill(). The examples I have seen declare a new Array() with a length of n, and .fill() it with a value. However, I have not seen any examples dealing with .push(), so I'm not even sure it is possible.
Example of what I'm looking for:
var my_array = [];
for (var i = 0; i < 5; i++) {
my_array.push(5);
};
Scenario:
I'm pulling values from three different arrays or objects to populate a single matrix that will be ran through a Munkres (Hungarian) algorithm, in order to avoid introducing another loop I would like to .push values to the matrix and use .fill() to repeat the value n times.
Example:
var s = […];
var a = […];
var p = […];
var matrix = [];
for (var i = 0; i < s.length; i++) {
var preferences = [];
for (var j = 0; j < p.length; j++ {
var pid = p[j];
for (var k = 0; k < a.length; k++ {
if (pid == a[k]) {
for (var l = 0; l < 5; l++) { // <-- THIS.
preferences.push(a[k]);
};
};
};
};
matrix.push(preferences);
};
You could use concat and fill:
preferences = preferences.concat(Array(5).fill(a[k]));
Trying to count possible combinations to get a targetTotal. Using powerSet returns the sum without adding itself. E.g [1,2,3,5] returns [3+1] for a targetSum of 4, whereas I expect to get [1+1+1+1], [2+2], [3+1].
Do you have any ideas how I could make it count itself first as a case?
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSums(numbers, targetSum) {
var sumSets = [];
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
sumSets.push(numberSet);
}
return sumSets;
}
Example invocation:
findSums([1,2,3,4,5],6); [[2,3], [1,4], [5], [1,1,1,1,1,1], [2,2,2], [3,3]]
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!
Use the following code (any loop for one item of the array 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:
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, []);
I found this solution. I'm sure it can be coded in a much nicer way. However, it works and I hope you find it useful
all_combinations(A){
var B = [];
for (var i = 0; i < A[0] + 1; i++) {
B.push([i]);
}
for (var i = 1; i < A.length; i++) {
var _tmp_array = [];
for (var j = 0; j < A[i] + 1; j++) {
for (var k = 0; k < B.length; k++) {
var _new_element = B[k].concat([j]);
_tmp_array.push(_new_element);
}
}
B = _tmp_array;
}
return B;
}
I come from a Ruby background, which features an enumerable class. In Ruby, I can easily find combinations of array elements.
array.combination(2).count
I know that JavaScript doesn't feature such built in functions, so I was wondering how I could implement this in JS. I was thinking something like
I have an array as follows
var numbers = [9,7,12]
var combos = []
for (var i = 0; i < numbers.length; i++) {
combos.push([numbers[i], numbers[i+1])
}
By the way, the possible combos are
[9,7], [9,12] and [7,12]
so by calling the length function on this array, 3 would be returned.
Any ideas?
How about:
for (var i = 0; i < numbers.length; i++)
for (var j = i + 1; j < numbers.length; j++)
combos.push([numbers[i], numbers[j]]);
Are you strictly talking about 2-combinations of the array or are you interested in a k-combinations solution?
Found this in this gist
function k_combinations(set, k) {
var i, j, combs, head, tailcombs;
if (k > set.length || k <= 0) {
return [];
}
if (k == set.length) {
return [set];
}
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
head = set.slice(i, i+1);
tailcombs = k_combinations(set.slice(i + 1), k - 1);
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
Here's a recursive function, which should work for any number:
function combination(arr, num) {
var r= [];
for(var i = 0 ; i < arr.length ; i++) {
if(num===1) r.push([arr[i]]);
else {
combination(arr.slice(i+1), num-1).forEach(function(val) {
r.push([].concat(arr[i], val));
});
}
}
return r;
} //combination
Working Fiddle