user1003382
user1003382

Reputation: 49

Function to return a multidimensional array of 0s

Imagine I had a function called multi0(Array) and I wanted it to take an Array as an argument.

If I did multi0([5]), it would return an array that looks like

[0,0,0,0,0]

If I did multi0([5,3]), it would return an array that looks like

[
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0],
    [0,0,0]
]

I attempted this with recursion, but it didn't work. How do you implement this?

Upvotes: 1

Views: 2034

Answers (2)

Yoav Kadosh
Yoav Kadosh

Reputation: 5175

try this:

function multi0(a,b) {
    x = new Array;
    for(var i=0;i<a;i++) {
        x[i] = new Array;
        for(var s=0;s<b;s++) {
            x[i][s] = 0;
        }
    }
    return x;
}

check it out here fiddle

Upvotes: 0

Guffa
Guffa

Reputation: 700910

Like this:

function multi0(arr) {
  if (arr.length == 0) {
    return 0;
  } else {
    var children = arr.slice(1);
    var result = [];
    for (var i = 0; i < arr[0]; i++) {
      result.push(multi0(children));
    }
    return result;
  }
}

http://jsfiddle.net/ffuH4/

Or the slightly longer but more effective:

function multi0(arr) {
  var result = [];
  if (arr.length == 1) {
    for (var i = 0; i < arr[0]; i++) {
      result.push(0);
    }
  } else {
    var children = arr.slice(1);
    for (var i = 0; i < arr[0]; i++) {
      result.push(multi0(children));
    }
  }
  return result;
}

Upvotes: 5

Related Questions