N-dimensional N^N array filled with N

63

3

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.

Adám

Posted 2017-02-28T16:48:37.493

Reputation: 37 779

If our language does not support arrays, what would be an acceptable output format? – Okx – 2017-02-28T16:54:55.953

@Okx JSON, or any other unambiguous array notation. – Adám – 2017-02-28T16:55:48.133

18Since "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. – user2357112 supports Monica – 2017-02-28T19:05:56.477

1Do all the arrays need to be distinct objects? – Neil – 2017-03-01T00:25:55.880

1@user2357112 I think that's more of a precondition type issue. I doubt the op actually expects the function to accept memory as input. – user64742 – 2017-03-01T04:31:19.773

2@TheGreatDuck Correct, but I'm pretty sure user2357112 meant it as a joke. – Adám – 2017-03-01T05:47:09.340

@Neil I don't understand. Can you elaborate? – Adám – 2017-03-01T05:50:15.637

Take the case N = 3. Am I allowed to write (unrolled) a = 3; a = [a, a, a]; a = [a, a, a]; a = [a, a, a]; or must I write a11 = [3, 3, 3]; a12 = [3, 3, 3]; a13 = [3, 3, 3]; a1 = [a11, a12, a13]; /* etc. for a2 and a3 */ a = [a1, a2, a3];? – Neil – 2017-03-01T09:55:01.200

@Neil Ah, they are pointers, so the if one sets the very first element of the first a to 2, all the elements of a become 2, whereas that isn't the case for the second a. The first is fine too, if it isn't too much work, I'd be interested in seeing both for comparison. – Adám – 2017-03-01T09:58:58.160

start="5">

  • and 6. seem expired.
  • < – sergiol – 2017-08-21T20:16:05.837

    @sergiol Now that there are plenty of answers, you can just use one of the Try it Online! links to generate the desired outputs. – Adám – 2017-08-21T20:21:23.590

    can I have a trailing comma at the end of the answer like "[1]," or "[[2,2],[2,2]]," – JoshM – 2018-06-05T19:37:33.013

    @JoshM You're supposed to return/output an array. – Adám – 2018-06-05T19:46:01.060

    @Adám nvm I figured it out – JoshM – 2018-06-05T20:18:01.810

    The hastebin links seem to be broken. They redirect me to the main site – Conor O'Brien – 2018-06-22T20:51:03.243

    Answers

    51

    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.

    xnor

    Posted 2017-02-28T16:48:37.493

    Reputation: 115 687

    3the scope trick is genius – Griffin – 2017-02-28T19:09:42.713

    +1, that eval trick really golfs down a lot of bytes – MilkyWay90 – 2019-03-26T01:28:53.153

    31

    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
    

    miles

    Posted 2017-02-28T16:48:37.493

    Reputation: 15 654

    6When I saw the challenge title, I thought of J immediately. Pretty cool that J even beats Jelly (the golfing language inspired by J). – Dane – 2017-02-28T18:56:59.110

    1There's also $~$~ which is equivalent while also repeating itself – miles – 2017-03-01T23:53:16.087

    2$~$~ translated to English... MONEY, get more of, MONEY, get more of... – Magic Octopus Urn – 2017-03-02T21:38:55.163

    12

    APL (Dyalog APL), 4 bytes

    ⍴⍨⍴⊢
    

    Try it online!

    Dennis

    Posted 2017-02-28T16:48:37.493

    Reputation: 196 637

    1

    Btw, ⍴⍨⍴⍨ works too, while looking cooler.

    – Adám – 2017-11-07T13:53:58.913

    12

    Mathematica, 22 20 bytes

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

    JungHwan Min

    Posted 2017-02-28T16:48:37.493

    Reputation: 13 290

    9

    R, 26

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

    n=scan();array(n,rep(n,n))
    

    Flounderer

    Posted 2017-02-28T16:48:37.493

    Reputation: 596

    is scan() necessary? – Adám – 2017-02-28T21:42:22.330

    Looking at the other answers, it seems like it either has to be a function or accept input somehow? – Flounderer – 2017-02-28T21:43:27.883

    1Right, I don't know R at all. I just thought that you could specify a function somehow instead. – Adám – 2017-02-28T21:58:05.653

    Yes, you can replace n=scan(); by function(n) but it makes it longer. – Flounderer – 2017-03-01T01:19:46.997

    can it be scan()%>%array(rep(.,.))? It uses magrittr operator – raymkchow – 2017-03-01T10:35:40.853

    pryr::f(array(n,rep(n,n))) creates an unnamed function instead of using scan, but doesn't save any bytes. – BLT – 2017-03-01T17:14:52.813

    5You can save one byte by putting the n assignment inside of array: array(n<-scan(),rep(n,n)). – rturnbull – 2017-03-02T08:49:01.307

    @raymkchow library(magrittr) adds quite a few bytes. – Gregor Thomas – 2017-03-02T22:06:00.560

    I've always wondered why R coders in this section don't just use a variable name instead of scan, as other do with their languages. – skan – 2017-03-17T00:36:20.660

    8

    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)))

    Arnauld

    Posted 2017-02-28T16:48:37.493

    Reputation: 111 334

    8

    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
    

    Riley

    Posted 2017-02-28T16:48:37.493

    Reputation: 11 345

    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). – Kevin Cruijssen – 2019-02-21T13:05:09.177

    1@KevinCruijssen I think this is one of the answers that gave us the idea to take implicitly input multiple times :) – Riley – 2019-02-21T14:23:21.763

    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. – Kevin Cruijssen – 2019-02-21T14:25:23.120

    8

    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.

    Ørjan Johansen

    Posted 2017-02-28T16:48:37.493

    Reputation: 6 914

    7

    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!

    rahnema1

    Posted 2017-02-28T16:48:37.493

    Reputation: 5 435

    @LuisMendo Rats, I was just going to post that one ;) – beaker – 2017-02-28T17:29:05.980

    @beaker Whoops :-) – Luis Mendo – 2017-02-28T17:31:18.120

    7

    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         
    

    nimi

    Posted 2017-02-28T16:48:37.493

    Reputation: 34 639

    We can do the same idea shorter with more builtin functions: f n=iterate(filter(>'#').show.(<$[1..n]))(show n)!!n. – Ørjan Johansen – 2017-03-01T00:44:27.467

    @ØrjanJohansen: that's a great idea. Please post it as a separate answer. – nimi – 2017-03-01T06:04:30.827

    Could you shave a byte with (#0)=show? Not too familiar with Haskell – Cyoce – 2017-03-01T23:56:55.767

    @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. – nimi – 2017-03-02T06:06:25.843

    6

    Python 2, 36 bytes

    -2 bytes thanks to @CalculatorFeline

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

    Try it online!

    Trelzevir

    Posted 2017-02-28T16:48:37.493

    Reputation: 987

    ~-n==(n-1). – CalculatorFeline – 2017-02-28T17:31:37.440

    Would it be possible to include a TIO link?

    – Adám – 2017-02-28T17:37:58.677

    1

    In fact, this! (-8 bytes due to optimized algorithm, +9 bytes to add output)

    – CalculatorFeline – 2017-02-28T17:41:19.503

    @CalculatorFeline You can put things in Header and Footer to avoid inclusion in byte count. – Adám – 2017-02-28T17:43:17.130

    1Aren't input and output required in full program submissions? – CalculatorFeline – 2017-02-28T17:47:34.870

    @CalculatorFeline I only meant to imply the default rules. I've removed the comment. – Adám – 2017-02-28T17:59:48.213

    6

    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  
    

    Suever

    Posted 2017-02-28T16:48:37.493

    Reputation: 10 257

    I can't really tell from MATL Online whether your submission does the right thing. looks like every answer is a wide matrix. – Adám – 2017-02-28T17:21:15.270

    4@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 – Luis Mendo – 2017-02-28T17:21:52.320

    5

    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
    

    Business Cat

    Posted 2017-02-28T16:48:37.493

    Reputation: 8 927

    5

    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]]]
    

    Jonathan Allan

    Posted 2017-02-28T16:48:37.493

    Reputation: 67 804

    Second 5-byte Jelly answer. Still unacceptably long compared to J :-) – Adám – 2017-02-28T18:54:40.727

    2...and not for want of trying :D – Jonathan Allan – 2017-02-28T18:55:34.793

    5

    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)));
        }
    
    }
    

    anacron

    Posted 2017-02-28T16:48:37.493

    Reputation: 151

    1can you replace i<=1 with i<2 ? – cliffroot – 2017-03-01T10:02:11.610

    Yes @cliffrott. That worked. thanks!! – anacron – 2017-03-01T10:04:55.480

    1You could save a few bytes with a lambda: (n,i)->{...} – None – 2017-03-02T14:50:09.127

    Java 8 lambdas ftw – None – 2017-03-02T22:03:02.537

    1Hmm, 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. – Jakob – 2018-06-24T01:24:53.037

    5

    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
    

    Neil

    Posted 2017-02-28T16:48:37.493

    Reputation: 95 035

    5

    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]]]
    

    Mitchell Spector

    Posted 2017-02-28T16:48:37.493

    Reputation: 3 392

    5

    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

    »€`¡
    

    dylnan

    Posted 2017-02-28T16:48:37.493

    Reputation: 4 993

    4

    Jelly, 5 bytes

    Wẋ³µ¡
    

    Try it online!

    Explanation

             Implicit input: N
       µ¡    Apply N times to input:
    Wẋ³        “N copies of”
    

    Lynn

    Posted 2017-02-28T16:48:37.493

    Reputation: 55 648

    4

    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)

    ovs

    Posted 2017-02-28T16:48:37.493

    Reputation: 21 408

    Why are your code lines reversed compared to your TIO link? – Adám – 2017-02-28T17:25:21.377

    You can replace c>1 with c to save 1 byte. (Markdown, stop deduplicating spaces across ```s) – CalculatorFeline – 2017-02-28T17:32:26.860

    @CalculatorFeline I don't think he can; that would c>0 in this particular case. – Erik the Outgolfer – 2017-02-28T17:34:12.160

    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

    – CalculatorFeline – 2017-02-28T17:36:15.530

    @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. – CalculatorFeline – 2017-02-28T17:43:25.360

    4

    Ruby, 28 26 bytes

    Thanks to Cyoce for saving 2 bytes!

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

    Stolen shamelessly from xnor's excellent answer.

    adrianmp

    Posted 2017-02-28T16:48:37.493

    Reputation: 1 592

    1Do you need those parens? – Cyoce – 2017-03-02T00:03:48.053

    4

    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.

    G B

    Posted 2017-02-28T16:48:37.493

    Reputation: 11 099

    3

    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!

    Ismael Miguel

    Posted 2017-02-28T16:48:37.493

    Reputation: 6 797

    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() – user59178 – 2017-03-01T09:28:55.743

    @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! – Ismael Miguel – 2017-03-01T09:38:50.220

    3

    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!

    smls

    Posted 2017-02-28T16:48:37.493

    Reputation: 4 352

    Use $_ instead to save a byte – Jo King – 2018-06-23T00:28:20.423

    @JoKing: I already use $_ as the inner block's parameter, so I can't use it as the outer block's parameter as well. – smls – 2018-08-23T21:46:06.293

    Yes, but $n and $_ always have the same value. Try it online!

    – Jo King – 2018-08-23T22:59:34.620

    3

    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

    cliffroot

    Posted 2017-02-28T16:48:37.493

    Reputation: 1 080

    3

    Rebol, 45 bytes

    func[n][array/initial append/dup copy[]n n n]
    

    draegtun

    Posted 2017-02-28T16:48:37.493

    Reputation: 1 592

    3

    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.

    Neil

    Posted 2017-02-28T16:48:37.493

    Reputation: 95 035

    +1 Wow, I wouldn't have expected that. All hail the humble .bat file! – Adám – 2017-03-01T20:13:27.280

    3

    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.

    MattPutnam

    Posted 2017-02-28T16:48:37.493

    Reputation: 521

    3

    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!

    Adám

    Posted 2017-02-28T16:48:37.493

    Reputation: 37 779

    3

    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!

    ceilingcat

    Posted 2017-02-28T16:48:37.493

    Reputation: 5 503

    3

    MathGolf, 5 4 bytes

    _{a*
    

    Try it online!

    Explanation using n = 2 (note that the outermost [] are not arrays, but are just there to show the stack)

    _      duplicate TOS (stack is [2, 2])
     {     loop 2 times (stack is [2])
      a    wrap in array ([2] => [[2]], [[2, 2]] => [[[2, 2]]])
       *   pop a, b : push(a*b) ([[2]] => [[2, 2]], [[[2, 2]]] => [[[2, 2], [2, 2]]])
    

    maxb

    Posted 2017-02-28T16:48:37.493

    Reputation: 5 754

    2

    Perl 6, 61 bytes

    my $x=prompt(0);my @a=$x xx$x;"@a=[@a] xx $x;".EVAL xx$x-1;
    

    Big rippof from the Python 2 answer, but converted :P

    Håvard Nygård

    Posted 2017-02-28T16:48:37.493

    Reputation: 341

    Instead of my $x=prompt(0);, you can use $_=get;. You also need to print or return the result somehow, but note that the rules of this site allow writing answers as functions or lambdas instead of of full programs, which is usually shorter in Perl 6.

    – smls – 2017-02-28T22:54:38.187

    2

    Clojure, 63 bytes

    #(loop[a(repeat % %)d 1](if(= d %)a(recur(repeat % a)(inc d))))
    

    This is a lambda function, usage is like so:

    (#(...) {input_no})
    

    ...where {input_no} is replaced with the number.

    Output for 3 is like this:

    (((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)))
    

    This uses Clojure's definition of lists, which are denoted as ().

    Ungolfed code and explanation:

    ; Defines the function
    (defn layered [n]
      ; Begins a loop with a variable depth of 1,
      ; and a list of n elements which are all n
      (loop [depth 1
             array (repeat n n)]
        ; If "depth" is equal to n, return the list
        (if (= depth n) array
          ; Else, continue on with the loop, with
          ; an incremented "depth"...
          (recur (inc depth)
            ; ...and a list which contains the
            ; list repeated n times
            (repeat n array)))))
    

    clismique

    Posted 2017-02-28T16:48:37.493

    Reputation: 6 600

    2

    SNOBOL4 (CSNOBOL4), 59 bytes

    	DEFINE('F(N)')
    F	F =ARRAY(DUPL(N ',',N - 1) N,N)	:(RETURN)
    

    Try it online!

    Defines a function that returns an ARRAY with the appropriate dimensions and filled with value N.

    Giuseppe

    Posted 2017-02-28T16:48:37.493

    Reputation: 21 077

    2

    Haskell, 51 bytes

    Other than the existing Haskell solutions this constructs a usable data type not just a string representation thereof (and is shorter):

    data L=N[L]|E Int
    f n=iterate(N.(<$[1..n]))(E n)!!n
    

    Try it online!

    Explanation / Ungolfed

    The reason why this is an interesting challenge in Haskell is that a solution to this challenge needs to return different deeply nested lists and Haskell (without importing external modules) does not support this. One workaround which turned out to be the golfiest, is to define our own data type:

    data NestedList = Nest [NestedList] | Entry Int
    

    Now we can just define a function f :: Int -> NestedList which is able to represent all the required data types:

    pow n = iterate (Nest . replicate n) (Entry n) !! n
    

    ბიმო

    Posted 2017-02-28T16:48:37.493

    Reputation: 15 345

    2

    Japt, 14 bytes

    _òU}g[UpU ÆUÃ]
    

    Try it online!

    Output is wrapped in an extra singleton array.

    Explanation:

              Æ Ã     #Create an array
               U      #Where every element is U
          UpU         #And the length is U^U
    _  }g[       ]    #Repeat this function U times:
     òU               # Cut into slices of length U
    

    Kamil Drakari

    Posted 2017-02-28T16:48:37.493

    Reputation: 3 461

    114 bytes; I was hoping it'd be shorter. – Shaggy – 2019-02-22T08:34:14.207

    1

    Python 3, 89 Bytes

    def f(x):
     r=[x for _ in range(x)]
     for _ in range(x-1):r=[r for _ in range(x)]
     print(r)
    

    sonrad10

    Posted 2017-02-28T16:48:37.493

    Reputation: 535

    1

    Lithp, 82 bytes

    (def f #N::((def i #N,I,K::((if(> I 0)((i N(- I 1)(list-fill N K)))K)))(i N N N)))
    

    Try it online!

    I tried implementing this as a list comprehension, but couldn't comprehend how to do it correctly. Instead I went for an implementation based on the JavaScript answer. Unfortunately, my language is fairly long-winded, and this is complicated by the fact that I lack shorthand and other useful features.

    A more readable version is available at the Try it Online link.

    Andrakis

    Posted 2017-02-28T16:48:37.493

    Reputation: 361

    1

    Hoon, 56 bytes

    |=
    n/@
    =+
    i=1
    |-
    ?:
    =(n i)
    (reap n n)
    (reap n $(i +(i)))
    

    Create a new function that takes an atom n. Make a variable i starting at 1, and start a loop: if i==n return a list with n elements of n, else return a list with n elements of the value returned by recursing to the start of the loop with i = i + 1.

    I'm a little bit upset that there's not really anything you can do to golf this in Hoon :/ The standard trick of using unnamed variables doesn't apply because it's longer to use lark syntax for once, due to the loop shifting the location of i.

    > =f |=
      n/@
      =+
      i=1
      |-
      ?:
      =(n i)
      (reap n n)
      (reap n $(i +(i)))
    > (f 1)
    ~[1]
    > (f 2)
    ~[~[2 2] ~[2 2]]
    > (f 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]]]
    > (f 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]]
      ]
    ]
    

    RenderSettings

    Posted 2017-02-28T16:48:37.493

    Reputation: 620

    1

    WendyScript, 34 bytes

    #:(x){<<j=[x]*x#i:1->x j=[j]*x/>j}
    #:(x){<<j=[x]*x#i:1->x j=[j]*x/>j}(2) // [[2, 2], [2, 2]]
    

    Try it online!

    Felix Guo

    Posted 2017-02-28T16:48:37.493

    Reputation: 211

    Is it not possible to have the link actually populate with the your code? – Adám – 2017-08-21T19:46:43.677

    I will have to add that functionality, I'll get back to you in 30 minutes but that's a good point. – Felix Guo – 2017-08-21T19:47:18.430

    @Adám updated link – Felix Guo – 2017-08-21T21:36:37.990

    1

    12-basic, 42 bytes

    A=[N=INPUT()]*N
    FOR I=2TO N
    A=[A]*N
    NEXT?A
    

    12Me21

    Posted 2017-02-28T16:48:37.493

    Reputation: 6 110

    1

    V, 14 bytes

    é,"aPÀñDÀpys0]
    

    Try it online!

    input

    é,               # write comma
      "aP            # paste register A (input)
         Àñ          # loop À (number in register A) times
           D         # cut to end of line
            Àp       # paste À times
              ysB]   # surround everything before comma in square brackets
    

    JoshM

    Posted 2017-02-28T16:48:37.493

    Reputation: 379

    This prints a trailing comma.. – ბიმო – 2018-06-30T21:30:09.673

    @BMO is the trailing comma a problem? it was never explicitly stated that it wasn't allowed. if it is a problem I can change it, it just adds one or two characters – JoshM – 2018-07-01T21:59:26.690

    1

    C (GCC), 53 bytes

    Since C "has" multidimensional arrays (i.e. chunks of memory plus automatic offset calculation), this is almost a reasonable solution. Still, it's mostly a joke and borders on non-competing.

    f(n){int s=pow(n,n),*p=malloc(s*8);wmemset(p,n,s);}
    

    Try It Online

    In the TIO I go through the ceremony of casting the result (which is an int) to the appropriate array type despite the fact that my array print function (appropriately) takes a generic pointer.

    While I can't demonstrate that the structure of the array is determined by f (it's not), I do include a flat printout of the elements of the output for an input of 3 using the multidimensional array element access syntax, to show that the layout of the returned memory matches that of the corresponding array type.

    Byte count

    • function: 51 bytes
    • compiler flags (-lm): 2 bytes

    Unportability

    • The result pointer is returned through an int, so this may not work for all heap addresses.
    • By using wmemset I require that the sizes of int and wchar_t are equal, and the scaling in the argument to malloc requires the sizes to be at most 8 bytes.
    • Implicit declaration madness. I don't even know why passing ints to an unprototyped pow that actually takes doubles seems to work correctly.
    • The function "returns" by (I think) just leaving the return value of wmemset in the proper register. This behavior may be particular to the x86 architecture.

    Jakob

    Posted 2017-02-28T16:48:37.493

    Reputation: 2 428

    42 bytes s;f(n){wmemset(malloc(4*s),n,s=pow(n,n));} – ceilingcat – 2018-06-24T08:12:14.467

    @ceilingcat Nice. But as far as I know neither C nor GCC defines the order of argument evaluation--what guarantees that will work? – Jakob – 2018-06-24T16:36:08.487

    1

    Julia 0.6, 23 bytes

    n->fill(n,fill(n,n)...)
    

    Try it online!

    The first argument to fill is the value to fill the new array with. The following arguments to that are the dimensions of the new array. Here we create those dimensions themselves using another fill call: we create an array of n ns, then splat that with ... so that the first fill call gets n number of dimension arguments, each with value n - so it creates an n-dimensional array where each dimension length is n, and filled with the value n.

    sundar - Reinstate Monica

    Posted 2017-02-28T16:48:37.493

    Reputation: 5 296

    1

    Pip -p, 12 bytes

    YaLaY[y]RLay
    

    Try it online!

    Explanation

    YaLaY[y]RLay
    Y             Yank into the y variable
     a            the first command-line argument, a
      La          Fixed-iterations loop, do the following a times:
         [y]       y wrapped in a list
            RLa    repeated a times (results in a list containing a copies of y)
        Y          Yank that list back into y
               y  After the loop, print y
    

    DLosc

    Posted 2017-02-28T16:48:37.493

    Reputation: 21 213

    0

    Perl 5, 34 bytes

    sub{eval'@_=[(@_)x$x];'x($x="@_")}
    

    Try it online!

    Dom Hastings

    Posted 2017-02-28T16:48:37.493

    Reputation: 16 415

    0

    Lua, 85 bytes

    function f(n,d,x)d=d or 2 x={}for i=1,n do x[i]=d>n and n or f(n,d+1)end return x end
    

    Try it online!

    (The TIO link contains a bit of extra code to print the table as Lua has no built-in way of printing a table's contents)

    Explanation

    function f(n, d, x)
      d = d or 2
      x = {}
      for i = 1, n do
        x[i] = d > n and n or f(n, d + 1)
      end
      return x
    end
    

    As you can probably see, f is a recursive function which takes the number N as n, and two other arguments, d and x. d is the depth, and is not used in the initial call, in which case it defaults to 2. x is not actually used as a parameter, but is there because the function requires a temporary local variable, and it is shorter to declare it as a parameter than to use the local keyword.

    IDid

    Posted 2017-02-28T16:48:37.493

    Reputation: 101