Javascript: Create a 10x10 array of 1s

18

3

Obviously this challenge would be trivial with separate functions and libraries, so they aren't allowed.

Your code must conform to an ECMAscript specification (any spec will do), so no browser-specific answers.

The array must be accessible after it is instantiated.

I have an answer that I'll withhold for now.

Note: this challenge is specific to javascript because it is notoriously inconvenient to make multi-dimensional arrays in javascript.

Shmiddty

Posted 2013-01-24T22:27:43.430

Reputation: 1 209

I'm at 57 characters. Is this a good score? – John Dvorak – 2013-01-24T23:12:36.470

Ok, definitely not :-) – John Dvorak – 2013-01-25T10:26:52.820

15Are you sure you don't just want this nice 1x1 array of 10s? [10] – kojiro – 2013-01-28T04:42:48.437

8Would that be [[10]]? – yingted – 2013-03-12T21:50:11.037

Answers

10

Javascript ES6, 30

(x=i=>Array(10).fill(i))(x(1))

ES6 in action :)

Afonso Matos

Posted 2013-01-24T22:27:43.430

Reputation: 312

2Hi, this question is like 2 years old. It's probably a better use of your JS code golfing skills to answer more recent questions ;) – George – 2015-06-18T22:47:54.307

6@George I don't think there's anything wrong with answering old challenges. (Some challenge authors will also update the accepted answer if a new winner comes along, no matter how old the challenge is.) – Martin Ender – 2015-06-19T07:18:11.200

2@MartinBüttner This answer is not elligible for being accepted as ES6 is younger(it came in 2015 :)) than this challenge, and Array.fill() is ES6 only :) – Katenkyo – 2015-06-19T08:24:52.803

I just answered because I saw other ES6 answers too. I don't think there is anything wrong with this. The author might update his question and others might take advantage of multiple ways of solving the problem above. – Afonso Matos – 2015-06-19T10:33:30.120

ES6 has been accepted long before its draft actually got frozen (that is in 2015, a few days back). I am not sure though whether that is correct or incorrect. – Optimizer – 2015-06-19T11:10:00.850

My ES6 answer on this question isn't even valid in the ES6 spec anymore :P – nderscore – 2015-06-19T14:06:15.177

One day I imagine it may be as simple as x=Matrix(10,10).fill(1). If that day ever comes, I will change that to be the accepted answer. – Shmiddty – 2015-06-19T21:28:33.140

@Martin Büttner, Looks like I was wrong ;) – George – 2015-06-23T06:51:14.167

One of the requirements is The array must be accessible after it is instantiated. You need another couple of characters to assign it to a variable (but would, currently, still have the shortest answer). – MT0 – 2015-06-23T13:40:12.013

27

Javascript, 34 bytes

for(r=[b=[i=10]];i--;r[i]=b)b[i]=1

Since it's apparently OK to make the rows equal by reference, I guess it's apparently OK to rely on that fact. This helps us shave off one for-loop by building the table at the same time as its rows. So, here's my new contestant.

Since r[0] and b[0] are overwritten during the loop, they can contain garbage. This gives us another free execution slot to shave off some commas. Sadly, r=b=[] won't do, since then they are equal by-ref.

Also, it scales well (99x99 is still 34 bytes), doesn't require ES5 (the new functions have terribly long names, anyways), and as a bonus, it's unreadable :-)

John Dvorak

Posted 2013-01-24T22:27:43.430

Reputation: 9 048

3Beautiful. Absolutely beautiful. – Briguy37 – 2013-01-25T16:27:31.797

1Damn, I ended up with: c=[b=[i=10]];while(i--)b[i]=c,c[i]=1. Should have known!!! – mowwwalker – 2013-01-27T22:35:36.137

19

ECMAScript 6 - 33 Characters

x=(y=[..."1111111111"]).map(x=>y)

Outputs a 10x10 array of "1"s.

This abuses the fact that the string "1111111111" has all the requisite properties to be treated as if it is an array so you can use the spread operator ... to transform it into an array of characters and then map it to a copy of the array with each element referencing the "original".

Or with only one variable name (for 35 characters):

x=(x=x=>[..."1111111111"])().map(x)

Or for extra confusion (but at 45 characters)

x=[];x[9]=x;x=[...x].map(y=>[...x].map(x=>1))

or (43 characters)

y=y=>[...x].map(x=>y);x=[];x[9]=x;x=y(y(1))

MT0

Posted 2013-01-24T22:27:43.430

Reputation: 3 373

Nice abuse of the ... operator! – nderscore – 2014-05-23T19:34:10.700

13

44 bytes

for(a=[i=10];i;)a[--i]=[1,1,1,1,1,1,1,1,1,1]

Previous version:

for(a=i=[];i^10;)a[i++]=[1,1,1,1,1,1,1,1,1,1]

copy

Posted 2013-01-24T22:27:43.430

Reputation: 6 466

Very clever update! – Shmiddty – 2013-01-25T04:40:30.323

for(a=[i=9];i;)a[i--]=[1,1,1,1,1,1,1,1,1,1] – AmericanUmlaut – 2013-01-25T10:25:22.640

1@AmericanUmlaut that doesn't work – copy – 2013-01-25T16:04:01.937

1I like ^ for != – John Dvorak – 2013-01-25T17:21:02.033

13

45 characters

x=[a=[1,1,1,1,1,1,1,1,1,1],a,a,a,a,a,a,a,a,a]

Each element points to the same array, but the spec doesn't mention anything against that!

Casey Chu

Posted 2013-01-24T22:27:43.430

Reputation: 1 661

4the spec says that "The array must be accessible after it is instantiated.". I guess that means you should have an extra x= at the beginning – Cristian Lupascu – 2013-01-25T13:21:22.340

a very nice solution nevertheless (+1) – Cristian Lupascu – 2013-01-25T15:46:09.483

That is not very practical though as a change to a value will reflect on all arrays. – Gabriele Petrioli – 2019-01-10T14:33:57.910

7

Javascript, 51

a=[];for(i=10;i;i--,a.push([1,1,1,1,1,1,1,1,1,1]));

Or if all indices are allowed to point to the same array:

Javascript, 41

a=[1,1,1,1,1,1,1,1,1,1];a=a.map(a.sort,a)

grc

Posted 2013-01-24T22:27:43.430

Reputation: 18 565

All of the indices now point to the same column, which is probably unwanted. (Try a[0][1] = 5; console.log(a[1][1])). – copy – 2013-01-25T01:13:42.393

Yeah I didn't see that. I've updated my answer. – grc – 2013-01-25T02:38:37.380

6

JavaScript, 45 44 Bytes

Best I have so far. (Still trying).

x=[];while(x.push([1,1,1,1,1,1,1,1,1,1])-10);

Shorter (thanks mellamokb!)

for(x=[];x.push([1,1,1,1,1,1,1,1,1,1])-10;);

Brigand

Posted 2013-01-24T22:27:43.430

Reputation: 1 137

Note that for is almost always preferable to while when golfing. The basic statement is the same length (while() vs for(;;)), but for gives you more flexibility. In this case, you could put x=[] in the initializer of the for and save one character. – mellamokb – 2013-01-25T14:49:45.330

@mellamokb, thanks for the tip :-) – Brigand – 2013-01-25T15:16:03.543

5

Javascript, 47

Since my original solution has been beaten, I will now post it.

for(a=[],i=10;i--;a[i]='1111111111'.split(''));

Unfortunately, 0x3FF.toString(2) isn't quite as efficient as just listing the string out, which isn't quite as efficient as just statically declaring the array.

You can shave off one character this way (46):

for(a=[],i=10;i--;a[i]=[1,1,1,1,1,1,1,1,1,1]);

You can save 2 more characters like so: (44)

for(a=[i=10];i--;)a[i]=[1,1,1,1,1,1,1,1,1,1]

Another 44 byte solution using JS 1.8 function expression closures (FF only atm):

x=(x=[1,1,1,1,1,1,1,1,1,1]).map(function()x)

Shmiddty

Posted 2013-01-24T22:27:43.430

Reputation: 1 209

1You can save one char by initializing i in a like this: a=[i=10] – codeporn – 2013-01-31T09:44:44.573

4

JavaScript, 57 bytes

r=eval("["+(A=Array(11)).join("["+A.join("1,")+"],")+"]")

Before golfing:

a=Array(11).join("1,");
b=Array(11).join("["+a+"],")
c=eval("["+b+"]")

Note: This needs ES5, so don't expect much from IE.

John Dvorak

Posted 2013-01-24T22:27:43.430

Reputation: 9 048

Wow! I wrote eval('a=['+(b=Array(11)).join('['+b.join("1,")+'],')+']'). Apart from having different quotes and my having the variable inside eval, these are exactly the same – mowwwalker – 2013-01-27T22:39:45.600

2a=eval("["+Array(11).join("[1,1,1,1,1,1,1,1,1,1],")+"]") has 56 – yingted – 2013-03-12T21:58:33.720

3

54

This has already been beaten, but here's my solution:

function x(){return[1,1,1,1,1,1,1,1,1,1]}x=x().map(x)

kojiro

Posted 2013-01-24T22:27:43.430

Reputation: 717

Arrow functions will do interesting things to JavaScript golfing. Now if only I could figure out how to trivially Curry builtins. – kojiro – 2013-01-25T04:56:49.667

You'd need to insert x= before x().map (or y=, etc) to make it accessible, right? – Shmiddty – 2013-01-25T04:56:51.583

@Schmiddty Yes, so updated. – kojiro – 2013-01-25T05:02:18.777

3

39 bytes

Using array comprehension in ECMAScript 7:

x=[x for(y in x=[1,1,1,1,1,1,1,1,1,1])]

nderscore

Posted 2013-01-24T22:27:43.430

Reputation: 4 912

There are no array comprehensions in ES6, that's an ES7 proposal. – Afonso Matos – 2015-06-19T14:19:35.023

@afonsomatos at the time I made this answer, it was still part of the ES6 draft. It's updated now though :) – nderscore – 2015-06-19T14:29:25.557

Replacing [1,1,1,1,1,1,1,1,1,1] with Array(10).fill(1) shaves 4 chars. – Shmiddty – 2015-06-19T21:36:56.493

2

56 characters

Rather long answer, but will be better for 100x100 etc.

for(a=[[i=k=0]];++i<100;m?0:a[k=i/10]=[1])a[k][m=i%10]=1

XzKto

Posted 2013-01-24T22:27:43.430

Reputation: 141

2

ES6, 54

It's not the shortest, but I thought I'd go for a different approach to what's already here.

a=(''+{}).split('').slice(0,10).map(_=>a.map(_=>1))

Cast an object to a string "[object Object]"
Split the string into chars ["[", "o", "b", ... "]" ]
Grab a slice of just 10
Map the result of mapping 1 onto the initial slice

Dan Prince

Posted 2013-01-24T22:27:43.430

Reputation: 1 467

Where can I test it? It doesn't work right in my FF. – Qwertiy – 2015-02-05T12:48:47.993

I'd missed out some parens, however, because a already existed that version seemed to have worked. Updated version should work in FF and node with the --harmony flags. – Dan Prince – 2015-02-05T14:31:03.710

Now it returns right array, but it's not assigned to any variable. – Qwertiy – 2015-02-05T15:27:14.053

2

Javascript, 36 chars (ECMA 6)

(a=[b=[]]).fill(b.fill(a[9]=b[9]=1))

Tested in my browser (Firefox on Ubuntu) and in the Codecademy Javascript interpreter

QuadmasterXLII

Posted 2013-01-24T22:27:43.430

Reputation: 881

1

61 for fun

eval("r=["+("["+(Array(11).join("1,"))+"],").repeat(11)+"]")

Maxime E

Posted 2013-01-24T22:27:43.430

Reputation: 11

0

Javascript - 64 63 59 characters

for(var a=b=[],i=100;i-->0;b[i%10]=1)if(i%10==0){a[i/10]=b;b=[]}

for(var a=b=[i=100];i-->0;b[i%10]=1)if(i%10==0){a[i/10]=b;b=[]}

One char saved by hiding the iterator in the array.

for(a=b=[1],i=100;i--;b[i%10]=1)if(i%10==0){a[i/10]=b;b=[]}

Saved some chars with Jans suggestions.

Readable version:

for(var a = b = [i = 100]; i-- > 0; b[i % 10] = 1) {
  if(i % 10 == 0) {
    a[i / 10] = b;
    b = [];
  }
}

Yes, it's not the shortest solution, but another approach without using readymade [1,1,1,1,1,1,1,1,1,1] arrays.

codeporn

Posted 2013-01-24T22:27:43.430

Reputation: 261

1Change i-->0 to i--. While the "downto" operator is nice, it's not really neccessary. ==0 could be shaved off by two bits as well. Also, leave out var. While normally useful, four useless bytes are just unacceptable here. – John Dvorak – 2013-01-25T18:06:19.360

0

Javascript 69 characters (for now)

b=[]
a=[]
for(i=100;i-->0;){
a.push(1)
if(i%10===0){b.push(a);a=[]}
}

Bobby Marinoff

Posted 2013-01-24T22:27:43.430

Reputation: 159

0

JavaScript (ES6), 35 bytes

A=Array(10).fill(Array(10).fill(1))

user84702

Posted 2013-01-24T22:27:43.430

Reputation: 1

1Setting a variable isn't an approved method of output. However, you can do f=>Array(10).fill(Array(10).fill(1)) (defining an anonymous function) for 36 bytes. – Rɪᴋᴇʀ – 2018-12-26T15:42:51.180

0

JavaScript 73

function h(){s="1111111111",r=[10],i=-1;while(++i<10){r[i]=s.split("");}}

bacchusbeale

Posted 2013-01-24T22:27:43.430

Reputation: 1 235

1r=[10], does nothing as you immediately overwrite r[0]. You don't need to declare s and could just do "1111111111".split("") but that is 22 characters whereas [1,1,1,1,1,1,1,1,1,1] is only 21 characters. – MT0 – 2014-05-25T07:18:21.360

0

Javascript ES6, 53

x="1".repeat(100).match(/.{10}/g).map(s=>s.split(""))

But the ones in the array are strings :)

Qwertiy

Posted 2013-01-24T22:27:43.430

Reputation: 2 697

0

Javscript ES6, 53

x=eval("["+("["+"1,".repeat(10)+"],").repeat(10)+"]")

Qwertiy

Posted 2013-01-24T22:27:43.430

Reputation: 2 697