Trying to create a function mCreate()
that given a set a numbers returns a multidimensional array (matrix):
mCreate(2, 2, 2)
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
When this functions handles just 2 levels of depth ie: mCreate(2, 2) //[[0, 0], [0, 0]]
I know to do 2 levels, you can use 2 nested for loops
but the problem I'm having is how to handle an n'th number of arguments.
Would this problem be better approached with recursion, otherwise how can I dynamically determine the number of nested for loops
I'm going to need given the number of arguments?
ps: the most performant way would be great but not essential
RE-EDIT - After using Benchmark.js to check perf the results were as follows:
BenLesh x 82,043 ops/sec ±2.56% (83 runs sampled)
Phil-P x 205,852 ops/sec ±2.01% (81 runs sampled)
Brian x 252,508 ops/sec ±1.17% (89 runs sampled)
Rick-H x 287,988 ops/sec ±1.25% (82 runs sampled)
Rodney-R x 97,930 ops/sec ±1.67% (81 runs sampled)
Fastest is Rick-H
@briancavalier also came up with a good solution JSbin:
const mCreate = (...sizes) => (initialValue) => _mCreate(sizes, initialValue, sizes.length-1, 0)
const _mCreate = (sizes, initialValue, len, index) =>
Array.from({ length: sizes[index] }, () =>
index === len ? initialValue : _mCreate(sizes, initialValue, len, index+1))
mCreate(2, 2, 2)(0)
One simple recursive answer is this (in ES2015):
JS Bin here
EDIT: I think I'd add the initializer in with a higher order function though:
Which could be used like:
JSBin of that
As suggested by @Pranav, you should use
arguments
object.Recursion + arguments object
The gist is to pass in the result of a
create
as the second argument ofcreate
except for the last (or the first depending on how you look at it) instance:DEMO
Using a loop we can build up array dimensions:
DEMO
Here's a non-recursive solution:
The JSON functions are used to mimic a deep clone, but that causes the function to be non-performant.
Recursive algorithms may be easier to reason about, but generally they're not required. In this particular case the iterative approach is simple enough.
Your problem consists of two parts:
0
-value elementsHere's an implementation of what I think you're trying to create:
Since writing the algorithm is only half of the solution, here's the test to verify our function actually performs the way we want it to. We'd typically use one of the gazillion test runners (e.g. mocha or AVA). But since I don't know your setup (if any), we'll just do this manually:
It's up to you to define and handle edge-cases, like
nested(3, 0)
,nested(0, 4)
,nested(3, -1)
ornested(-1, 2)
.