Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #10550 > unrolled thread

Initialize multi-dimensional array

Started byArchos <raul.san@sent.com>
First post2012-01-24 15:09 -0800
Last post2012-01-27 20:09 +0000
Articles 11 — 8 participants

Back to article view | Back to comp.lang.javascript


Contents

  Initialize multi-dimensional array Archos <raul.san@sent.com> - 2012-01-24 15:09 -0800
    Re: Initialize multi-dimensional array Denis McMahon <denismfmcmahon@gmail.com> - 2012-01-25 09:56 +0000
    Re: Initialize multi-dimensional array Andreas Bergmaier <andber93@web.de> - 2012-01-25 11:48 +0100
      Re: Initialize multi-dimensional array Archos <raul.san@sent.com> - 2012-01-25 04:37 -0800
        Re: Initialize multi-dimensional array Richard Cornford <Richard@litotes.demon.co.uk> - 2012-01-25 06:35 -0800
      Re: Initialize multi-dimensional array Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-01-25 19:39 +0100
        Re: Initialize multi-dimensional array Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-01-28 01:42 +0100
    Re: Initialize multi-dimensional array "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-01-25 09:38 -0800
    Re: Initialize multi-dimensional array Dr J R Stockton <reply1204@merlyn.demon.co.uk> - 2012-01-25 19:33 +0000
      Re: Initialize multi-dimensional array Ross McKay <au.org.zeta.at.rosko@invalid.invalid> - 2012-01-26 11:56 +1100
        Re: Initialize multi-dimensional array Dr J R Stockton <reply1204@merlyn.demon.co.uk> - 2012-01-27 20:09 +0000

#10550 — Initialize multi-dimensional array

FromArchos <raul.san@sent.com>
Date2012-01-24 15:09 -0800
SubjectInitialize multi-dimensional array
Message-ID<81f35d2e-80d0-45aa-965a-c0093cbf4fbf@b23g2000yqn.googlegroups.com>
I want to initialize a multidimensional array to a determined value,
i.e. an array of dimensions [2][4] initialized to 1.

I can do:
var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
Array(4); }
for (var i0=0; i0<2; i0++){ for (var i1=0; i1<4; i1++){ a2[i0]
[i1]=1; }}

or shorter:
var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
Array(4); for (var i1=0; i1<4; i1++){ a2[i0][i1]=1; }}

But is there any another way to do it shorter? Without use `var a2 =
[[1,1,1,1], [1,1,1,1]]`

Thanks in advance!

[toc] | [next] | [standalone]


#10558

FromDenis McMahon <denismfmcmahon@gmail.com>
Date2012-01-25 09:56 +0000
Message-ID<4f1fd1c5$0$30329$a8266bb1@newsreader.readnews.com>
In reply to#10550
On Tue, 24 Jan 2012 15:09:00 -0800, Archos wrote:

> I want to initialize a multidimensional array to a determined value,
> i.e. an array of dimensions [2][4] initialized to 1.

var arr = new Array ( new Array(1,2,3,4), new Array(2,4,6,8), new Array
(3,6,9,12) );

Rgds

Denis McMahon

[toc] | [prev] | [next] | [standalone]


#10563

FromAndreas Bergmaier <andber93@web.de>
Date2012-01-25 11:48 +0100
Message-ID<jfoml6$ve6$1@news.albasani.net>
In reply to#10550
Archos schrieb:
> I want to initialize a multidimensional array to a determined value
>
> I can do:
> var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
> Array(4); }
> for (var i0=0; i0<2; i0++){ for (var i1=0; i1<4; i1++){ a2[i0]
> [i1]=1; }}
>
> or shorter:
> var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
> Array(4); for (var i1=0; i1<4; i1++){ a2[i0][i1]=1; }}
>
> But is there any another way to do it shorter? Without use `var a2 =
> [[1,1,1,1], [1,1,1,1]]`

What do you mean with "shorter"? Less code? Faster execution? If you 
don't want to use array literals, there will always be two loops:

var a=[];for(var i=0;i<2;i++){a[i]=[];for(var j=0;j<4;j++)a[i][j]=1;}

There might be tricky expressions with less code, but you don't really 
want them.

  Bergi

[toc] | [prev] | [next] | [standalone]


#10572

FromArchos <raul.san@sent.com>
Date2012-01-25 04:37 -0800
Message-ID<ef57156d-830b-43a0-befe-adc822240feb@f11g2000yql.googlegroups.com>
In reply to#10563
On Jan 25, 10:48 am, Andreas Bergmaier <andbe...@web.de> wrote:
> Archos schrieb:
>
> > I want to initialize a multidimensional array to a determined value
>
> > I can do:
> > var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
> > Array(4); }
> > for (var i0=0; i0<2; i0++){ for (var i1=0; i1<4; i1++){ a2[i0]
> > [i1]=1; }}
>
> > or shorter:
> > var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
> > Array(4); for (var i1=0; i1<4; i1++){ a2[i0][i1]=1; }}
>
> > But is there any another way to do it shorter? Without use `var a2 =
> > [[1,1,1,1], [1,1,1,1]]`
>
> What do you mean with "shorter"? Less code? Faster execution? If you
> don't want to use array literals, there will always be two loops:
>
> var a=[];for(var i=0;i<2;i++){a[i]=[];for(var j=0;j<4;j++)a[i][j]=1;}
>
> There might be tricky expressions with less code, but you don't really
> want them.
>
>   Bergi

I mean less code, and using simple '[]' is saved some space, but is it
implemented in the main browsers or I could have any problem by its
use?

Which has a faster execution (array literal or '[]')?

[toc] | [prev] | [next] | [standalone]


#10574

FromRichard Cornford <Richard@litotes.demon.co.uk>
Date2012-01-25 06:35 -0800
Message-ID<1a4be77a-5a58-4834-954e-f5bd294b0ba4@t8g2000yqg.googlegroups.com>
In reply to#10572
On Jan 25, 12:37 pm, Archos wrote:
> On Jan 25, 10:48 am, Andreas Bergmaier wrote:
<snip>
>> There might be tricky expressions with less code, but
>> you don't really want them.
>
> I mean less code,

Why, what is the problem with having more code?

> and using simple '[]' is saved some space, but is it
> implemented in the main browsers or I could have any problem
> by its use?

Array literals where formalised in ECMA 262 3rd Ed at the end
of 1999, so has been around for long enough to be universally
implemented in web browser's javascript engines.

> Which has a faster execution (array literal or '[]')?

[] is an array literal; a literal declaration for an empty array.

Richard.

[toc] | [prev] | [next] | [standalone]


#10580

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2012-01-25 19:39 +0100
Message-ID<1934720.aqSPkdTlGX@PointedEars.de>
In reply to#10563
Andreas Bergmaier wrote:

> Archos schrieb:
>> I want to initialize a multidimensional array to a determined value
>>
>> I can do:
>> var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
>> Array(4); }
>> for (var i0=0; i0<2; i0++){ for (var i1=0; i1<4; i1++){ a2[i0]
>> [i1]=1; }}
>>
>> or shorter:
>> var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
>> Array(4); for (var i1=0; i1<4; i1++){ a2[i0][i1]=1; }}
>>
>> But is there any another way to do it shorter? Without use `var a2 =
>> [[1,1,1,1], [1,1,1,1]]`
> 
> What do you mean with "shorter"? Less code? Faster execution? If you
> don't want to use array literals, there will always be two loops:

No.
 
> var a=[];for(var i=0;i<2;i++){a[i]=[];for(var j=0;j<4;j++)a[i][j]=1;}
        ^^                           ^^
JFYI: You are using two Array literals here, of course.
 
> There might be tricky expressions with less code, but you don't really
> want them.

A matter of opinion.  Surely

  var a = [];
  a.length = 5;
  a = a.join("1").split("").map(function (el) { return +el; });
  a = [a, a.slice()];

is a more elegant solution to this problem.


PointedEars
-- 
var bugRiddenCrashPronePieceOfJunk = (
    navigator.userAgent.indexOf('MSIE 5') != -1
    && navigator.userAgent.indexOf('Mac') != -1
)  // Plone, register_function.js:16

[toc] | [prev] | [next] | [standalone]


#10661

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2012-01-28 01:42 +0100
Message-ID<2236669.bzG4ezAXRf@PointedEars.de>
In reply to#10580
Thomas 'PointedEars' Lahn wrote:

> Andreas Bergmaier wrote:
>> var a=[];for(var i=0;i<2;i++){a[i]=[];for(var j=0;j<4;j++)a[i][j]=1;}
>         ^^                           ^^
> JFYI: You are using two Array literals here, of course.
>  
>> There might be tricky expressions with less code, but you don't really
>> want them.
> 
> A matter of opinion.  Surely
> 
>   var a = [];
>   a.length = 5;
>   a = a.join("1").split("").map(function (el) { return +el; });
>   a = [a, a.slice()];
> 
> is a more elegant solution to this problem.

It should be noted that this approach can also be used with multi-digit 
numbers and any other value:

  var a = [];
  a.length = 5;
  a = a.join(",12").split(",").map(function (el) { return +el; });
  a.shift();
  a = [a, a.slice()];

However more elegant, the map() method is not backwards compatible (so it 
requires comparably expensive emulation) and it is expensive itself because 
the function needs to be called multiple times.  Also, the need for 
additional shift() (or pop(), if you use "12," instead) with multi-character 
values reduces its elegance.

So a combination of the classical looping approach and the more elegant 
slicing approach (which performs the element assignment natively, therefore 
should be cheaper than an explicit loop) appears to be the best solution:

  function getFilledMatrix(rows, columns, fill)
  {
    var a = [];

    var tmp = [];
    tmp.length = columns;
    
    for (var j = 0; j < columns; ++j)
    {
      tmp[j] = fill || 0;
    }

    for (var i = 0; i < rows; ++i)
    {
      if (i == 0)
      {
        a.push(tmp);
      }
      else
      {
        a.push(tmp.slice());
      }
    }

    return a;
  }


PointedEars
-- 
When all you know is jQuery, every problem looks $(olvable).

[toc] | [prev] | [next] | [standalone]


#10579

From"Michael Haufe (TNO)" <tno@thenewobjective.com>
Date2012-01-25 09:38 -0800
Message-ID<7d3ab98f-4edd-4e84-bd53-3ad408b34f07@b23g2000yqn.googlegroups.com>
In reply to#10550
On Jan 24, 5:09 pm, Archos <raul....@sent.com> wrote:
> I want to initialize a multidimensional array to a determined value,
> i.e. an array of dimensions [2][4] initialized to 1.
>
> I can do:
> var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
> Array(4); }
> for (var i0=0; i0<2; i0++){ for (var i1=0; i1<4; i1++){ a2[i0]
> [i1]=1; }}
>
> or shorter:
> var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
> Array(4); for (var i1=0; i1<4; i1++){ a2[i0][i1]=1; }}
>
> But is there any another way to do it shorter? Without use `var a2 =
> [[1,1,1,1], [1,1,1,1]]`
>
> Thanks in advance!

Use an Array Comprehension.

[toc] | [prev] | [next] | [standalone]


#10583

FromDr J R Stockton <reply1204@merlyn.demon.co.uk>
Date2012-01-25 19:33 +0000
Message-ID<tWjEMKGVkFIPFwTj@invalid.uk.co.demon.merlyn.invalid>
In reply to#10550
In comp.lang.javascript message <81f35d2e-80d0-45aa-965a-c0093cbf4fbf@b2
3g2000yqn.googlegroups.com>, Tue, 24 Jan 2012 15:09:00, Archos
<raul.san@sent.com> posted:

>I want to initialize a multidimensional array to a determined value,
>i.e. an array of dimensions [2][4] initialized to 1.
>
>I can do:
>var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
>Array(4); }
>for (var i0=0; i0<2; i0++){ for (var i1=0; i1<4; i1++){ a2[i0]
>[i1]=1; }}
>
>or shorter:
>var a2 = new Array(2); for (var i0=0; i0<2; i0++){ a2[i0]=new
>Array(4); for (var i1=0; i1<4; i1++){ a2[i0][i1]=1; }}
>
>But is there any another way to do it shorter? Without use `var a2 =
>[[1,1,1,1], [1,1,1,1]]`

Slightly.  Use [] instead of new Array(n).  A while loop counting down
is probably shorter & faster than a for loop counting up, and you can
combine the decrement and the "was that zero?" test.

        var X, j, k, A = []
        j = 2 ; do { A[--j] = X = []
          k = 4 ; do { X[--k] = 1 }
            while (k) }
          while (j) ;

if your '4' is both small and constant, and you don't mind setting to
"1" rather than 1, this is shorter

var X, j, A = []
j = 2 ; do { A[--j] = X = "1111".split("") } while (j) ;

and if it is variable but under about 54, and ditto,

var X, j, A = []
j = 2, k = 99
do { A[--j] = X = (Math.pow(2, k)-1).toString(2).split("") } while (j) ;

Inadequately tested.

-- 
 (c) John Stockton, nr London, UK.    ?@merlyn.demon.co.uk     Turnpike v6.05.
 Website  <http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
 PAS EXE etc. : <http://www.merlyn.demon.co.uk/programs/> - see in 00index.htm
 Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.

[toc] | [prev] | [next] | [standalone]


#10588

FromRoss McKay <au.org.zeta.at.rosko@invalid.invalid>
Date2012-01-26 11:56 +1100
Message-ID<3g81i7l6qma04ij6jsef0hjprjochsvq4q@4ax.com>
In reply to#10583
On Wed, 25 Jan 2012 19:33:41 +0000, Dr J R Stockton wrote:

>[...] A while loop counting down
>is probably shorter & faster than a for loop counting up, [...]

No.

http://jsperf.com/caching-array-length/4
-- 
Ross McKay, Toronto, NSW Australia
"You can't control what you can't measure" - Tom DeMarco

[toc] | [prev] | [next] | [standalone]


#10657

FromDr J R Stockton <reply1204@merlyn.demon.co.uk>
Date2012-01-27 20:09 +0000
Message-ID<giyHRmBRSwIPFwB3@invalid.uk.co.demon.merlyn.invalid>
In reply to#10588
In comp.lang.javascript message <3g81i7l6qma04ij6jsef0hjprjochsvq4q@4ax.
com>, Thu, 26 Jan 2012 11:56:11, Ross McKay <au.org.zeta.at.rosko@invali
d.invalid> posted:

>On Wed, 25 Jan 2012 19:33:41 +0000, Dr J R Stockton wrote:
>
>>[...] A while loop counting down
>>is probably shorter & faster than a for loop counting up, [...]
>
>No.
>
>http://jsperf.com/caching-array-length/4


I prefer to rely on my own tests, done with a large enough loop for time
to begin to matter.

var A, J, K_ = 777 // increase     v put code in those
D0_ = new Date()
Q_ = K_ ;
D1_ = new Date()
Q_ = K_ ; while (Q_--) { }
D2_ = new Date()
Q_ = K_ ; while (Q_--) { A = [] ; J = K_ ; while (--J) A[J] = J }
D3_ = new Date()
Q_ = K_ ; while (Q_--) { A = [] ; for (J = 0 ; J < K_ ; J++) A[J] = J }
D4_ = new Date()
Q_ = [D1_-D0_, D2_-D1_, D3_-D2_, D4_-D3_] // times // Demo 6

The while loop is clearly shorter.  And I find it faster in three
browsers out of five.

-- 
 (c) John Stockton, Surrey, UK.  ?@merlyn.demon.co.uk   Turnpike v6.05   MIME.
   Web  <http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
 Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
 Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.javascript


csiph-web