66
\$\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\$
15
  • \$\begingroup\$ If our language does not support arrays, what would be an acceptable output format? \$\endgroup\$
    – Okx
    Feb 28, 2017 at 16:54
  • 22
    \$\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\$ Feb 28, 2017 at 19:05
  • 1
    \$\begingroup\$ Do all the arrays need to be distinct objects? \$\endgroup\$
    – Neil
    Mar 1, 2017 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\$
    – user64742
    Mar 1, 2017 at 4:31
  • 3
    \$\begingroup\$ @TheGreatDuck Correct, but I'm pretty sure user2357112 meant it as a joke. \$\endgroup\$
    – Adám
    Mar 1, 2017 at 5:47

55 Answers 55

1
2
3
\$\begingroup\$

Rebol, 45 bytes

func[n][array/initial append/dup copy[]n n n]
\$\endgroup\$
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\$
3
\$\begingroup\$

05AB1E, 2 bytes

Try it online or verify the first \$[1,5]\$ test cases.

: Uses a Bash script to execute the 05AB1E code, so it'll use the (implicit) input within the test suite. If the number would be on the stack instead of as input, it won't work for \$n=2\$ (no idea why..): see this traditional test suite, where every output is correct except for \$n=2\$.

Explanation:

F   # Loop the (implicit) input amount of times:
 и  #  Repeat the (implicit) input the current values amount of times (as list)
    # (after which the resulting nested list is output implicitly)
\$\endgroup\$
3
\$\begingroup\$

tinylisp, 76 bytes

Since tinylisp was our most recent LYAL, I figured I had to at least post one answer in the lang. Embarrassingly, this answer (in a golfing dialect of lisp) is just as long as the Common Lisp solution

(load library
(d _(q((N D $)(i D(_ N(s D 1)(repeat-val $ N))$
(q((N)(_ N N N

Try it online!

This defines a helper function _ that takes three arguments, the number of times to repeat each layer N, the current depth of the iteration D (counting down, so deepest depth is zero), and an accumulator $. Depending on depth, this function either returns the accumulator (at depth zero), or uses the library builtin repeat-val to repeat the current accumulator N times, and passes that on to the next depth of the recursion. Then the actual function, A, is defined, which takes a single argument N in, and calls _ with that as all three arguments.

Non-library solution, 86 bytes

This was my first attempt to do this, without using the builtin library (which has rather ungolfy names), but it unfortunately turned out rather longer.

(d _(q((X N D I $)(i D(i I(_ X N D(s I 1)(c X $))(_ $ N(s D 1)N()))X
(q((N)(_ N N N N(

Try it online!

This works much the same as the library solution, but manually defines the behavior of repeat-val, which requires taking two extra arguments in the helper function, which takes the value X the current depth is repeating, the number of repetitions on each depth N, the current depth D (counting down to zero), the number of repetitions remaining in this depth I, and an accumulator $. The proper function A works much the same, taking N calling _ with the proper arguments. (in this case N for the first four, and nil () for the accumulator)

\$\endgroup\$
2
  • \$\begingroup\$ Here's a Try it online! link. Also, since anonymous function solutions are allowed, you don't have to include the (d A in your solution (though you do still need it for TIO). \$\endgroup\$
    – DLosc
    Apr 14 at 16:20
  • \$\begingroup\$ @DLosc oh ty for the TIO link! I meant to add it when posting, but it slipped my mind, also good shout about making the actual function anonymous \$\endgroup\$
    – des54321
    Apr 14 at 17:10
2
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – smls
    Feb 28, 2017 at 22:54
2
\$\begingroup\$

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)))))
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
2
  • \$\begingroup\$ 42 bytes s;f(n){wmemset(malloc(4*s),n,s=pow(n,n));} \$\endgroup\$
    – ceilingcat
    Jun 24, 2018 at 8:12
  • \$\begingroup\$ @ceilingcat Nice. But as far as I know neither C nor GCC defines the order of argument evaluation--what guarantees that will work? \$\endgroup\$
    – Jakob
    Jun 24, 2018 at 16:36
2
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 14 bytes; I was hoping it'd be shorter. \$\endgroup\$
    – Shaggy
    Feb 22, 2019 at 8:34
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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]]
  ]
]
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
3
  • \$\begingroup\$ Is it not possible to have the link actually populate with the your code? \$\endgroup\$
    – Adám
    Aug 21, 2017 at 19:46
  • \$\begingroup\$ I will have to add that functionality, I'll get back to you in 30 minutes but that's a good point. \$\endgroup\$
    – Felix Guo
    Aug 21, 2017 at 19:47
  • \$\begingroup\$ @Adám updated link \$\endgroup\$
    – Felix Guo
    Aug 21, 2017 at 21:36
1
\$\begingroup\$

12-basic, 42 bytes

A=[N=INPUT()]*N
FOR I=2TO N
A=[A]*N
NEXT?A
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ This prints a trailing comma.. \$\endgroup\$ Jun 30, 2018 at 21:30
  • \$\begingroup\$ @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 \$\endgroup\$
    – JoshM
    Jul 1, 2018 at 21:59
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Factor + arrays.shaped, 39 bytes

[ 3 dupn <array> swap repeated-shaped ]

Try it online!

repeated-shaped Takes a sequence of dimensions (i.e. a shape) and an element and creates an array from them. The rest of the code turns 4 into { 4 4 4 4 } 4, for example.

\$\endgroup\$
1
\$\begingroup\$

Jelly, 3 bytes

ḷⱮ¡

Try it online!

Like Lynn's solution which heavily inspired this, a full program only.

  ¡    Repeat [input] times, starting with the input on the left and right:
 Ɱ     Produce an array containing, for every element of the right argument,
ḷ      the left argument.

Although dyadic ¡, rather than reusing its right argument, uses the previous left argument for each successive iteration, in this case either behavior would do the same thing--since each intermediate result has the same length as the (implicitly rangified) initial input.

\$\endgroup\$
1
\$\begingroup\$

Pari/GP, 33 bytes

n->for(i=1,a=n,a=vector(n,x,a));a

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Vyxal, 2 bytes

(ẋ

Try it Online!

\$\endgroup\$
0
\$\begingroup\$

Perl 5, 34 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Zsh, 74 bytes

try it online!

f(){for i ({1..$1})z+=($2);<<<($z)}
for j ({1..$1})k=`f $1 ${k:-$1}`;<<<$k

Zsh doesn't have multi dimensional arrays but it can do arrays of strings. Here we build up string $k by plugging it into f, then taking that result as the new $k, iterating N times ($1).

\$\endgroup\$
1
2

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.