71
\$\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\$ Commented Feb 28, 2017 at 16:54
  • 24
    \$\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\$ Commented Feb 28, 2017 at 19:05
  • 1
    \$\begingroup\$ Do all the arrays need to be distinct objects? \$\endgroup\$ Commented 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\$ Commented Mar 1, 2017 at 4:31
  • 3
    \$\begingroup\$ @TheGreatDuck Correct, but I'm pretty sure user2357112 meant it as a joke. \$\endgroup\$ Commented Mar 1, 2017 at 5:47

66 Answers 66

4
\$\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\$
4
\$\begingroup\$

Uiua, 4 bytes

↯▽.. 

Try it!

↯▽.. . # duplicate . # duplicate ▽ # keep ↯ # reshape 
\$\endgroup\$
1
  • \$\begingroup\$ A fun one: |1 ⍥|'↯|.. (repeat reshape n n times to n). Also ⍥'↯,.. that leaves n below the answer. \$\endgroup\$ Commented Oct 12, 2023 at 7:07
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\$
2
  • \$\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\$ Commented Mar 1, 2017 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\$ Commented Mar 1, 2017 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\$

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\$

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\$

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\$
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\$ Commented Apr 14, 2022 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\$ Commented Apr 14, 2022 at 17:10
3
\$\begingroup\$

BQN, 4 bytes

⥊˜⥊⊢ 

Anonymous tacit function; takes an integer and returns an N-dimensional array. Try it at BQN online!

Explanation

Exactly the same as Dennis's APL answer, though independently derived.

The Reshape builtin takes a shape (list of integer dimensions) on the left and an array of values on the right. It creates an array of the given shape, filled with values taken from the original array. If either argument is a bare integer, it is promoted to a list containing that integer.

With example argument 3:

⥊˜ reshapes the argument with itself as the shape. The result is a 3-element 1-dimensional array of 3's: ⟨ 3 3 3 ⟩.

returns the argument unchanged: 3.

So ⥊˜ ⥊ ⊢ is equivalent to ⟨ 3 3 3 ⟩ ⥊ 3: reshape 3 into a 3 by 3 by 3 array.

\$\endgroup\$
1
  • \$\begingroup\$ ⥊˜⥊˜ looks cooler, imo. \$\endgroup\$ Commented May 13 at 7:13
3
\$\begingroup\$

K (ngn/k), 9 bytes

{(x#x)#x} 

Try it online!

There's probably a way to make this tacit.

\$\endgroup\$
1
  • \$\begingroup\$ Variation to make tacit: #/3# \$\endgroup\$ Commented Dec 16, 2022 at 7:05
3
\$\begingroup\$

Arturo, 20 bytes

$=>[@.of:@.of:<=<=&] 

Try it

Huh?

In Arturo, you can initialize a block of values like this:

array.of: 5 2 ; [2 2 2 2 2] 

You can also give it a shape:

array.of: [5 3] 2 ; [[2 2 2] [2 2 2] [2 2 2] [2 2 2] [2 2 2]] 

@ is syntax sugar for array.

$=> is syntax sugar for function [n].

<=<=& Means push the input to the stack and duplicate it twice.

So putting it all together, $=>[@.of:@.of:<=<=&] is the same as:

function [n][ array.of: array.of: n n n ] 

Or perhaps more clearly:

function [n][ shape: array.of: n n return array.of: shape n ] 
\$\endgroup\$
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\$ Commented 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\$ Commented 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\$ Commented 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\$ Commented Feb 22, 2019 at 8:34
2
\$\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\$
2
\$\begingroup\$

Pari/GP, 33 bytes

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

Try it online!

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

Vyxal, 2 bytes

(ẋ 

Try it Online!

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

Thunno 2, 3 bytes

{Wọ 

Attempt This Online!

Explanation

{Wọ # Implicit input { # Repeat input number of times: W # Wrap top of stack into a list ọ # Repeat input number of times # Implicit output 
\$\endgroup\$
2
\$\begingroup\$

J-uby, 28 bytes

~:^%(~:**%(:& &~:*|:|&-[I])) 

Attempt This Online!

\$\endgroup\$
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\$ Commented 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\$ Commented Aug 21, 2017 at 19:47
  • \$\begingroup\$ @Adám updated link \$\endgroup\$ Commented 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\$ Commented 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\$ Commented 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\$

Go, 150 bytes

func f(n int)[]any{return g(n,n)} func g(n,d int)(L[]any){if d<1{return} for i:=0;i<n;i++{var e any if d<2{e=n}else{e=g(n,d-1)} L=append(L,e)} return} 

Attempt This Online!

Call with f(n). Returns an []any, that can be casted to a f(n).([]int),f(n).([][]int),f(n).([][][]int),f(n).([][][][]int), etc.

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

Nim, 100 bytes

include xmltree macro f(n):auto=(var N=n.intval a=n;for i in 1..N:a=nnkBracket.newTree a.repeat N a) 

Try it in Wandbox

Ungolfed:

include xmltree macro f(node): auto = var N = node.intval a = node for i in 1..N: a = newTree(nnkBracket, repeat(a, N) a 
  • xmltree internally imports macros and sequtils libraries. Because they're not exported - we can access them only if we include the library.
  • sequtils.repeat works similar to Python's something * n
  • UFCS allows us to rewrite a(b,c) as b.a c to save 1 byte
  • In Nim - the last expression in parenthesis is a value of that expression e.g. (foo();a) == a
  • The last expression in procedure/macro is implicitly returned e.g. proc b():int=0 is same as proc b():int=return 0

If the task would allow tuples, we could shave off another 12 bytes:

Nim, 88 bytes

include xmltree macro f(n):auto=(var N=n.intval a=n;for i in 1..N:a=newPar a.repeat N a) 

This will generate:

(1) ((2,2),(2,2)) and so on ... 
\$\endgroup\$
2
  • \$\begingroup\$ Why do you assume tuples are not allowed? \$\endgroup\$ Commented May 13 at 7:03
  • \$\begingroup\$ @Adám in Nim tuple type is essentialy a object/struct with index access to it's fields, not a list of values. So, I am not sure if it qualifies as array replacement. \$\endgroup\$ Commented May 13 at 8:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.