62
\$\begingroup\$

In: Enough memory and a positive integer N

Out: N-dimensional N^N array filled with N, where N^N means N terms of N-by-N-by-N-by...

Examples:

1: [1] which is a 1D array (a list) of length 1, containing a single 1

2: [[2,2],[2,2]] which is a 2D array (a table) with 2 rows and 2 columns, filled with 2s

3: [[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]]] which is a 3D array (a cube) with 3 layers, 3 rows, and 3 columns, filled with 3s

4: [[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]]]

5 and 6: Please see one of the answers.

\$\endgroup\$
  • \$\begingroup\$ If our language does not support arrays, what would be an acceptable output format? \$\endgroup\$ – Okx Feb 28 '17 at 16:54
  • 17
    \$\begingroup\$ Since "Enough memory" is part of the input, I want to see an answer that controls a robot to actually take the memory as input and plug it in before using it. \$\endgroup\$ – user2357112 Feb 28 '17 at 19:05
  • 1
    \$\begingroup\$ Do all the arrays need to be distinct objects? \$\endgroup\$ – Neil Mar 1 '17 at 0:25
  • 1
    \$\begingroup\$ @user2357112 I think that's more of a precondition type issue. I doubt the op actually expects the function to accept memory as input. \$\endgroup\$ – The Great Duck Mar 1 '17 at 4:31
  • 2
    \$\begingroup\$ @TheGreatDuck Correct, but I'm pretty sure user2357112 meant it as a joke. \$\endgroup\$ – Adám Mar 1 '17 at 5:47

47 Answers 47

50
\$\begingroup\$

Python, 32 bytes

lambda n:eval('['*n+'n'+']*n'*n)

Try it online!

Makes a string like "[[[n]*n]*n]*n" with n multiplcations, and evaluates it as Python code. Since the evaluation happens within the function scope, the variable name n evaluates to the function input.

\$\endgroup\$
  • 3
    \$\begingroup\$ the scope trick is genius \$\endgroup\$ – Griffin Feb 28 '17 at 19:09
  • \$\begingroup\$ +1, that eval trick really golfs down a lot of bytes \$\endgroup\$ – MilkyWay90 Mar 26 at 1:28
31
\$\begingroup\$

J, 4 bytes

$~#~

Try it online!

Explanation

$~#~  Input: integer n
  #~  Create n copies of n
$~    Shape n into an array with dimensions n copies of n
\$\endgroup\$
  • 6
    \$\begingroup\$ When I saw the challenge title, I thought of J immediately. Pretty cool that J even beats Jelly (the golfing language inspired by J). \$\endgroup\$ – Dane Feb 28 '17 at 18:56
  • 1
    \$\begingroup\$ There's also $~$~ which is equivalent while also repeating itself \$\endgroup\$ – miles Mar 1 '17 at 23:53
  • 2
    \$\begingroup\$ $~$~ translated to English... MONEY, get more of, MONEY, get more of... \$\endgroup\$ – Magic Octopus Urn Mar 2 '17 at 21:38
12
\$\begingroup\$

APL (Dyalog APL), 4 bytes

⍴⍨⍴⊢

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Btw, ⍴⍨⍴⍨ works too, while looking cooler. \$\endgroup\$ – Adám Nov 7 '17 at 13:53
12
\$\begingroup\$

Mathematica, 22 20 bytes

(t=Table)@@t[#,#+1]&

(* or *)

Table@@Table[#,#+1]&
\$\endgroup\$
9
\$\begingroup\$

R, 26

This is the obvious answer but perhaps there is something cleverer?

n=scan();array(n,rep(n,n))
\$\endgroup\$
  • \$\begingroup\$ is scan() necessary? \$\endgroup\$ – Adám Feb 28 '17 at 21:42
  • \$\begingroup\$ Looking at the other answers, it seems like it either has to be a function or accept input somehow? \$\endgroup\$ – Flounderer Feb 28 '17 at 21:43
  • 1
    \$\begingroup\$ Right, I don't know R at all. I just thought that you could specify a function somehow instead. \$\endgroup\$ – Adám Feb 28 '17 at 21:58
  • \$\begingroup\$ Yes, you can replace n=scan(); by function(n) but it makes it longer. \$\endgroup\$ – Flounderer Mar 1 '17 at 1:19
  • 5
    \$\begingroup\$ You can save one byte by putting the n assignment inside of array: array(n<-scan(),rep(n,n)). \$\endgroup\$ – rturnbull Mar 2 '17 at 8:49
8
\$\begingroup\$

JavaScript (ES6),  44  40 bytes

f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k

Demo

f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k

console.log(JSON.stringify(f(1)))
console.log(JSON.stringify(f(2)))
console.log(JSON.stringify(f(3)))
console.log(JSON.stringify(f(4)))

\$\endgroup\$
8
\$\begingroup\$

Haskell, 52 bytes

f n=iterate(filter(>'"').show.(<$[1..n]))(show n)!!n

Try it online!

Inspired by @nimi's answer, but using more predefined functions.

  • Uses iterate and !! instead of a recursive help function.
  • Instead of constructing list delimiters "by hand", uses filter(>'"').show to format a list of strings, then stripping away the extra " characters.
\$\endgroup\$
8
\$\begingroup\$

05AB1E (legacy), 6 5 bytes

-1 thanks to Kevin Cruijssen

F¹.D)

Try it online!

F     # For 0 .. input
 ¹.D) # Push <input> copies of the result of the last step as an array
\$\endgroup\$
  • \$\begingroup\$ The leading D can be removed because the input is used implicitly again (not sure if this was a thing when you posted the answer, but you don't need the explicit D anymore now). \$\endgroup\$ – Kevin Cruijssen Feb 21 at 13:05
  • 1
    \$\begingroup\$ @KevinCruijssen I think this is one of the answers that gave us the idea to take implicitly input multiple times :) \$\endgroup\$ – Riley Feb 21 at 14:23
  • \$\begingroup\$ Ah ok. I was indeed expecting it to not be implicitly yet at the time of posting, but realized that after posting my comment (which I edited). ;) Sometimes it's funny how much explicit things are being done by old answer (usually pre-2017), and how much shorter it can be done now. \$\endgroup\$ – Kevin Cruijssen Feb 21 at 14:25
7
\$\begingroup\$

Octave, 35 33 25 23 20 bytes

@(N)ones(N+!(1:N))*N

Try it online!

@(N)ones(N*ones(1,N))*N

@(N)repmat(N,N*ones(1,N))

Thanks to @LuisMendo saved 8 bytes

@(N)ones(num2cell(!(1:N)+N){:})*N

Try it online!

Previous answer:

@(N)repmat(N,num2cell(!(1:N)+N){:})

Try it online!

\$\endgroup\$
  • \$\begingroup\$ @LuisMendo Rats, I was just going to post that one ;) \$\endgroup\$ – beaker Feb 28 '17 at 17:29
  • \$\begingroup\$ @beaker Whoops :-) \$\endgroup\$ – Luis Mendo Feb 28 '17 at 17:31
7
\$\begingroup\$

Haskell, 62 bytes

n#0=show n
n#l='[':tail((',':)=<<n#(l-1)<$[1..n])++"]"
f n=n#n

Usage example: f 2 -> "[[2,2],[2,2]]". Try it online!.

Haskell's strict type system prevents a function that returns nested lists of different depths, so I construct the result as a string.

How it works:

n#l=                         n with the current level l is
    '[':                     a literal [ followed by
           n#(l-1)<$[1..n]   n copies of   n # (l-1)
        (',':)=<<            each prepended by a , and flattened into a single list
      tail                   and the first , removed
                  ++"]"      followed by a literal ]

n#0=show n                   the base case is n as a string

f n=n#n                      main function, start with level n         
\$\endgroup\$
  • \$\begingroup\$ We can do the same idea shorter with more builtin functions: f n=iterate(filter(>'#').show.(<$[1..n]))(show n)!!n. \$\endgroup\$ – Ørjan Johansen Mar 1 '17 at 0:44
  • \$\begingroup\$ @ØrjanJohansen: that's a great idea. Please post it as a separate answer. \$\endgroup\$ – nimi Mar 1 '17 at 6:04
  • \$\begingroup\$ Could you shave a byte with (#0)=show? Not too familiar with Haskell \$\endgroup\$ – Cyoce Mar 1 '17 at 23:56
  • \$\begingroup\$ @Cyoce: No, that's a syntax error. For a correct syntax I could flip the arguments and use (#)0=show, but all definitions of a function must have the same number of arguments. The second line (n#l='['...) needs two arguments, so the first line must also have two arguments. \$\endgroup\$ – nimi Mar 2 '17 at 6:06
6
\$\begingroup\$

MATL, 8 bytes

ttY"l$l*

Try it at MATL Online (I have added some code showing the actual size of the output since all n-dimensional outputs in MATL are shown as 2D matrices where all dimensions > 2 are flattened into the second dimension).

Explanation

        % Implicitly grab the input (N)
tt      % Make two copies of N
Y"      % Perform run-length decoding to create N copies of N
l$1     % Create a matrix of ones that is this size  
*       % Multiply this matrix of ones by N
        % Implicitly display the result  
\$\endgroup\$
  • \$\begingroup\$ I can't really tell from MATL Online whether your submission does the right thing. looks like every answer is a wide matrix. \$\endgroup\$ – Adám Feb 28 '17 at 17:21
  • 4
    \$\begingroup\$ @Adám Dimensions beyond the second are displayed as collapsed into the second. So the example shows a 3x9 array instead of the produced 3x3x3 array. If you add Zy at the end of the code it tells the actual size \$\endgroup\$ – Luis Mendo Feb 28 '17 at 17:21
6
\$\begingroup\$

Python 2, 36 bytes

-2 bytes thanks to @CalculatorFeline

a=n=input()
exec"a=[a]*n;"*n
print a

Try it online!

\$\endgroup\$
  • \$\begingroup\$ ~-n==(n-1). \$\endgroup\$ – CalculatorFeline Feb 28 '17 at 17:31
  • \$\begingroup\$ Would it be possible to include a TIO link? \$\endgroup\$ – Adám Feb 28 '17 at 17:37
  • 1
    \$\begingroup\$ In fact, this! (-8 bytes due to optimized algorithm, +9 bytes to add output) \$\endgroup\$ – CalculatorFeline Feb 28 '17 at 17:41
  • \$\begingroup\$ @CalculatorFeline You can put things in Header and Footer to avoid inclusion in byte count. \$\endgroup\$ – Adám Feb 28 '17 at 17:43
  • 1
    \$\begingroup\$ Aren't input and output required in full program submissions? \$\endgroup\$ – CalculatorFeline Feb 28 '17 at 17:47
5
\$\begingroup\$

CJam, 12 bytes

ri:X{aX*}X*p

Try it online!

Explanation

ri:X          Read an integer from input, store it in X (leaves it on the stack)
    {   }X*   Execute this block X times:
     a          Wrap the top of stack in an array
      X*        Repeat the array X times
           p  Print nicely
\$\endgroup\$
5
\$\begingroup\$

Jelly, 5 bytes

⁾Wẋẋv

Try it online!

How?

⁾Wẋẋv - Main link: n                            e.g.       3
⁾Wẋ   - character pair literal ['W','ẋ']                  "Wẋ"
   ẋ  - repeat list n times                               "WẋWẋWẋ"
    v - evaluate as Jelly code with input n          eval("WẋWẋWẋ", 3)
      - ...
        WẋWẋ... - toEval: n                e.g. 3
        W        - wrap                        [3]
         ẋ       - repeat list n times         [3,3,3]
          Wẋ     - wrap and repeat            [[3,3,3],[3,3,3],[3,3,3]]
            ...  - n times total             [[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]]]
\$\endgroup\$
  • \$\begingroup\$ Second 5-byte Jelly answer. Still unacceptably long compared to J :-) \$\endgroup\$ – Adám Feb 28 '17 at 18:54
  • 2
    \$\begingroup\$ ...and not for want of trying :D \$\endgroup\$ – Jonathan Allan Feb 28 '17 at 18:55
5
\$\begingroup\$

Java 97 96 95 bytes

Object c(int n,int i){Object[]a=new Object[n];for(int j=0;j<n;)a[j++]=i<2?n:c(n,i-1);return a;}

Ungolfed:

public class N_Dim {

    public static Object create(int n) {
        return create(n, n);
    }

    public static Object create(int n, int i) {
        Object[] array = new Object[n];
        for(int j=0;j<n;j++) {
            array[j] = i<2?n:create(n, i - 1);
        }
        return array;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString((Object[]) create(3)));
    }

}
\$\endgroup\$
  • 1
    \$\begingroup\$ can you replace i<=1 with i<2 ? \$\endgroup\$ – cliffroot Mar 1 '17 at 10:02
  • \$\begingroup\$ Yes @cliffrott. That worked. thanks!! \$\endgroup\$ – anacron Mar 1 '17 at 10:04
  • 1
    \$\begingroup\$ You could save a few bytes with a lambda: (n,i)->{...} \$\endgroup\$ – user18932 Mar 2 '17 at 14:50
  • \$\begingroup\$ Java 8 lambdas ftw \$\endgroup\$ – user47018 Mar 2 '17 at 22:03
  • 1
    \$\begingroup\$ Hmm, looks like this takes extra input. You'll need to make a separate method of just one parameter in order for this to be valid. \$\endgroup\$ – Jakob Jun 24 '18 at 1:24
5
\$\begingroup\$

JavaScript (ES6), 38 bytes

f=(n,m=n)=>m?Array(n).fill(f(n,m-1)):n

The memory-hungry version of this is 45 bytes:

f=(n,m=n)=>m?[...Array(n)].map(_=>f(n,m-1)):n
\$\endgroup\$
5
\$\begingroup\$

Bash + GNU utilities, 117 bytes

n=$[$1**$1]
seq -f$1o%.fd$n+1-p $n|dc|rev|sed -r "s/(0+|$[$1-1]*).*$/\1/;s/^(0*)/\1$1/;s/^1/[1]/"|tr \\n0$[$1-1] \ []

Try it online!


The program essentially counts from 0 to (n^n)-1 in base n, where n is the input. For each base-n number k in the count, it does the following:

  1. If k ends with at least one digit 0, print a '[' for each digit 0 at the end of k.
  2. Print n.
  3. If k ends with at least one digit n-1, print a ']' for each digit n-1 at the end of k.

(The value n=1 needs to have brackets added as a special case. This input value also generates some output to stderr, which can be ignored under standard PPCG rules.)

Maybe there's a shorter way to implement this idea.


Sample run:

./array 3
[[[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]]]
\$\endgroup\$
5
\$\begingroup\$

Jelly, 4 bytes

R»µ¡

Try it online!

R»µ¡
R     Range. 2 -> [1, 2]
 »    Max between left arg and right arg. Vectorizes. -> [2, 2]
  µ   Separates into a new chain.
   ¡  Repeat 2 times. After another iteration this yields [[2, 2], [2, 2]].

Same thing but with a single monad and no need for the chain separator:

4 bytes

»€`¡
\$\endgroup\$
4
\$\begingroup\$

Jelly, 5 bytes

Wẋ³µ¡

Try it online!

Explanation

         Implicit input: N
   µ¡    Apply N times to input:
Wẋ³        “N copies of”
\$\endgroup\$
4
\$\begingroup\$

Python 3, 57 53 50 38 bytes

f=lambda n,c=0:n-c and[f(n,c+1)*n]or 1

Try it online!


-4 bytes thanks to @CalculatorFeline


34 bytes:

f=lambda c,n:c and[f(c-1,n)*n]or 1

Needs to be called as f(4,4)

\$\endgroup\$
  • \$\begingroup\$ Why are your code lines reversed compared to your TIO link? \$\endgroup\$ – Adám Feb 28 '17 at 17:25
  • \$\begingroup\$ You can replace c>1 with c to save 1 byte. (Markdown, stop deduplicating spaces across `s) \$\endgroup\$ – CalculatorFeline Feb 28 '17 at 17:32
  • \$\begingroup\$ @CalculatorFeline I don't think he can; that would c>0 in this particular case. \$\endgroup\$ – Erik the Outgolfer Feb 28 '17 at 17:34
  • \$\begingroup\$ Then change the end to <space>n. Problem solved and bonus–more bytes saved! :D (So spaces at the end of inline code is possible, but not the beginning? That's strange...) TIO link \$\endgroup\$ – CalculatorFeline Feb 28 '17 at 17:36
  • \$\begingroup\$ @Adám: On TIO to allow the main function to be assigned in the header and here to keep the main function on the last line. \$\endgroup\$ – CalculatorFeline Feb 28 '17 at 17:43
4
\$\begingroup\$

Ruby, 28 26 bytes

Thanks to Cyoce for saving 2 bytes!

->n{eval'['*n+'n'+']*n'*n}

Stolen shamelessly from xnor's excellent answer.

\$\endgroup\$
  • 1
    \$\begingroup\$ Do you need those parens? \$\endgroup\$ – Cyoce Mar 2 '17 at 0:03
4
\$\begingroup\$

Ruby, 27 bytes

->a{(z=a).times{z=[z]*a};z}

Only 1 byte more but using a different approach instead of the 'eval' trick from xnor's wonderful Python answer.

\$\endgroup\$
3
\$\begingroup\$

Perl 6, 25 bytes

{($^n,{$_ xx$n}...*)[$n]}

Starts with n, and iteratively applies the "repeat n times" transformation n times, each time creating an additional level of List nesting.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Use $_ instead to save a byte \$\endgroup\$ – Jo King Jun 23 '18 at 0:28
  • \$\begingroup\$ @JoKing: I already use $_ as the inner block's parameter, so I can't use it as the outer block's parameter as well. \$\endgroup\$ – smls Aug 23 '18 at 21:46
  • \$\begingroup\$ Yes, but $n and $_ always have the same value. Try it online! \$\endgroup\$ – Jo King Aug 23 '18 at 22:59
3
\$\begingroup\$

PHP, 70 62 bytes

This is the simplest I can come up with.

for(;$i++<$n=$argv[1];)$F=array_fill(0,$n,$F?:$n);print_r($F);

Takes the input as the first argument and prints the resulting array on the screen.


Thanks to @user59178 for saving me 8 bytes!

\$\endgroup\$
  • \$\begingroup\$ Pre-assigning variables like that is unnecessary, as is $l. Dropping the $i=0, & replacing $lwith $n saves 7 bytes. An additional byte can be saved by not assigning $F, assigning $n in the conditional and using a ternary $F?:$n in the array_fill() \$\endgroup\$ – user59178 Mar 1 '17 at 9:28
  • \$\begingroup\$ @user59178 I don't know if this is what you had in mind or not, but, thank you for the tips. You've saved me 8 bytes! \$\endgroup\$ – Ismael Miguel Mar 1 '17 at 9:38
3
\$\begingroup\$

Clojure, 36 bytes

#(nth(iterate(fn[a](repeat % a))%)%)

Iterates function which repeats its argument n times, it produces infinite sequence of such elements and then takes its nth element.

See it online

\$\endgroup\$
3
\$\begingroup\$

Rebol, 45 bytes

func[n][array/initial append/dup copy[]n n n]
\$\endgroup\$
3
\$\begingroup\$

Batch, 141 bytes

@set t=.
@for /l %%i in (2,1,%1)do @call set t=%%t%%,.
@set s=%1
@for /l %%i in (1,1,%1)do @call call set s=[%%%%t:.=%%s%%%%%%]
@echo %s%

Batch doesn't actually have arrays so this just prints the string representation of an array. Explanation: The first two lines build up a repeated pattern of N .s separated by N-1 ,s in the variable t. The fourth line then uses this as a substitution pattern N times to create the N-dimensional array. The double call is necessary because of how the for and set statements work. First, the for command substitutes variables. As it happens, all of my % signs are doubled, so this does nothing except to unquote them all, resulting in call call set s=[%%t:.=%s%%%]. It then repeats the resulting statement N times. Each time, the call command substitutes variables. At this point, the s variable only has a single set of %s, so it gets substituted, resulting in (e.g.) call set s=[%t:.=[2,2]%]. The inner call then substitutes the t variable, resulting in (e.g.) set s=[[2,2],[2,2]], performing the desired assignment. The final value of s is then printed.

\$\endgroup\$
  • \$\begingroup\$ +1 Wow, I wouldn't have expected that. All hail the humble .bat file! \$\endgroup\$ – Adám Mar 1 '17 at 20:13
3
\$\begingroup\$

Clojure, 49 bytes

(defmacro r[n]`(->> ~n ~@(repeat n`(repeat ~n))))

Not the shortest Clojure example, but I amused myself with the quoting and unquoting.

\$\endgroup\$
3
\$\begingroup\$

I, 7 bytes

I got this from my colleague, the creator of I.

#Bbhph~

#Bb     the copy # function Bound to binding
   hp  hook the argument to (the right of) the power function (repeat)
     h~hook the argument to the left ~ (of the entire resulting function)

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Common Lisp, 128 102 95 79 bytes

(defun f(x &optional y)(if(if y(< y 2))x(fill(make-list x)(f x(if y(1- y)x)))))

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.